HttpContext.Current.Request.Form.AllKeys in ASP.NET CORE version

bbusdriver picture bbusdriver · Apr 7, 2017 · Viewed 12.8k times · Source
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
   string value = HttpContext.Current.Request.Form[key];
}

What is the .net core version of the above code? Seems like .net core took out AllKeys and replaced it with Keys instead. I tried to convert the above code to the .net core way, but it throws an invalid operation exception.

HttpContext.Request.Form = 'HttpContext.Request.Form' threw an exception of type 'System.InvalidOperationException'

Converted code:

foreach (string key in HttpContext.Request.Form.Keys)
{      
}

Answer

Gabriel Robert picture Gabriel Robert · Apr 8, 2017

Your could use this:

var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());

In that case, you can iterate over your dictionary or you can access values directly:

dict["Hello"] = "World"