ASP.NET 5: Reading form values

With new HttpContext in ASP.NET MVC 6 we will also get new request class. One markable change is how form variables are read from request. As there is no key-value collection with form variables that is filled by default when request is created we have to read form values asynchronously. Here’s the example how to do it.

As far as I understand then the decision to not load form variables by default is related to keeping HttpContext object graph minimal. New request object has asynchronous method called GetFormAsync() and we will use this method to load form variables.

public async Task<IActionResult> ShowVars()
    var output = new StringBuilder();
    output.AppendLine("Form vars:<br />");
    foreach (var item in await Context.Request.GetFormAsync())
        output.Append(": ");
        output.AppendLine("<br />");
    return Content(output.ToString());

One thing to notice – items in collection have type KeyValuePair<string, string[]>, so there can be more than one value for each form variable. This why I call FirstOrDefault() extension method on form values (yes, it’s not absolutely correct but this is just example). To find out more take a look at default implementation of GetFormAsync() method.

Wrapping up

HttpContext in next version of ASP.NET MVC is very small. Reading form variables is good example of how HttpContext object graph is held small. Variables are read on-demand basis and if your application doesn’t give MVC any reason to go for form variables then by default form variables are not touched.

See also

Leave a Reply

Your email address will not be published. Required fields are marked *