Is there a way to handle form post data in a Web Api controller?

Viewed 36367

In ASP.NET MVC , one can access the form post data:

var thisData = Request.Form["this.data"];

Is it possible to achieve the same functionality in a Web API ApiController?

5 Answers

If you just have an HttpRequestMessage, you have a couple of options:

By referencing System.Net.Http.Formatting, you can use the ReadAsFormDataAsync() extension method.

var formData = await message.Content.ReadAsFormDataAsync();

If you don't want to include that library, you can do the same thing manually by using the HttpUtility helper class in System.Web.

public async Task<NameValueCollection> ParseFormDataAsync(HttpRequestMessage message)
{
    string formString = await message.Content.ReadAsStringAsync();
    var formData = HttpUtility.ParseQueryString(formString);
    return formData;
}
Related