如何在ASP.NET Core中修改HttpContext.Request.Form

Her*_*ahl 4 httpcontext asp.net-core

我有一个HttpContext.Request对象,该对象的Form数据有误,我想对其进行修复,并以正确的方式发送正确的HttpContext。HttpContext.Request.Form是只读的,但是如果不是,则只需执行以下操作即可;HttpContext.Request.Form [“ a”] =“ a的正确值”;

因此,在管道中执行此操作的最佳位置在哪里。是否可以通过反射访问HttpContext.Request.Form写操作?

Her*_*ahl 5

这比我想的要容易。我正在我的中间件中执行此操作,该中间件用于更正传入的不良表格数据。

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);
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,FormCollection是只读的,但是HttpContext.Request对象因此不允许我替换整个Form。