Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify HttpContext.Request.Form in asp.net core

I have an HttpContext.Request object that has data in the Form that is wrong and I want to fix it up and send the correct HttpContext on its way. HttpContext.Request.Form is readonly, but if it wasn't I would have simply done the following; HttpContext.Request.Form["a"] = "the correct value for a";

So, where is the best place in the pipeline to do this. Is it possible to make the HttpContext.Request.Form write accessable via reflection?

like image 929
Herb Stahl Avatar asked Mar 09 '17 17:03

Herb Stahl


People also ask

How use HttpContext current in ASP.NET Core?

ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.

What is HttpContext in ASP.NET Core?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.

What is HttpContext HTTP request and Httpresponse?

HttpRequest is a subset of HttpContext . In other words, the HttpContext includes the response, the request, and various other data that's not relevant to a specific request or response; such as the web application, cached data, server settings and variables, session state, the authenticated user, etc.


1 Answers

This was easier than I thought. I am doing this in my middleware which is there to correct bad form data that came in.

public async Task Invoke(HttpContext context)
{
    ....
    NameValueCollection fcnvc = context.Request.Form.AsNameValueCollection();
    fcnvc.Set("a", "the correct value of a");
    fcnvc.Set("b", "a value the client forgot to post");
    Dictionary<string, StringValues> dictValues = new Dictionary<string, StringValues>();
    foreach (var key in fcnvc.AllKeys)
    {
      dictValues.Add(key, fcnvc.Get(key));
    }
    var fc = new FormCollection(dictValues);
    context.Request.Form = fc;
    ....
    await _next.Invoke(context);
}

Interestingly the FormCollection is readonly, but the HttpContext.Request object is not thus allowing me to replace the entire Form.

like image 79
Herb Stahl Avatar answered Sep 20 '22 21:09

Herb Stahl