我有一个 HttpContext.Request 对象,其表单中的数据是错误的,我想修复它并发送正确的 HttpContext。
HttpContext.Request.Form 是只读的,但如果不是,我就会简单地执行以下操作;
HttpContext.Request.Form["a"] = "a 的正确值";
那么,管道中执行此操作的最佳位置在哪里。
是否可以通过反射使 HttpContext.Request.Form 写入可访问?
这比我想象的要容易。我在我的中间件中执行此操作,该中间件用于纠正传入的错误格式数据。
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 对象不允许我替换整个表单。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)