13
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)
{      
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
bbusdriver
  • 1,577
  • 3
  • 26
  • 58

3 Answers3

24

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"
Gabriel Robert
  • 3,012
  • 2
  • 18
  • 36
0

Another option is:

StringValues s; 

Request.Form.TryGetValue("KeyName", out s);
if (s.Count == 1)
 {
   string value = s.ToString();
 }
Jim B
  • 420
  • 3
  • 10
-1
var data = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());

foreach (var item in data)
{
    if (item.Key.Contains("hello"))
    {
        // ?
    }
    else if (item.Key.Contains("world"))
    {
        // ?
    }
}
Alessandro
  • 305
  • 4
  • 12