如何在ASP.NET Core中修改HttpContext.Request.Form [英] How to modify HttpContext.Request.Form in asp.net core
问题描述
我有一个HttpContext.Request对象,该对象的Form数据有误,我想对其进行修复,并以正确的方式发送正确的HttpContext. HttpContext.Request.Form是只读的,但是如果不是,我将简单地执行以下操作; HttpContext.Request.Form ["a"] ="a的正确值";
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";
因此,在管道中执行此操作的最佳位置在哪里. 是否可以通过反射访问HttpContext.Request.Form写操作?
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?
推荐答案
这比我想象的要容易.我正在我的中间件中执行此操作,该中间件可以纠正输入的错误表格数据.
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);
}
有趣的是,FormCollection是只读的,但是HttpContext.Request对象不允许我替换整个Form.
Interestingly the FormCollection is readonly, but the HttpContext.Request object is not thus allowing me to replace the entire Form.
这篇关于如何在ASP.NET Core中修改HttpContext.Request.Form的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!