HttpContext.Current.Request.Form.AllKeys in ASP.NET CORE version
Asked Answered
S

3

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)
{      
}
Shouse answered 7/4, 2017 at 18:8 Comment(1)
What's the message of the exception?Pepillo
C
25

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"
Chantey answered 8/4, 2017 at 13:30 Comment(1)
var result= dict["Hello"] ;Stickseed
I
0

Another option is:

StringValues s; 

Request.Form.TryGetValue("KeyName", out s);
if (s.Count == 1)
 {
   string value = s.ToString();
 }
Ides answered 7/9, 2022 at 18:24 Comment(0)
V
-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"))
    {
        // ?
    }
}
Verism answered 9/6, 2020 at 23:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.