gpt4 book ai didi

c# - 如何在asp.net core中修改HttpContext.Request.Form

转载 作者:行者123 更新时间:2023-12-02 01:31:25 25 4
gpt4 key购买 nike

我有一个 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 对象不允许我替换整个表单。

关于c# - 如何在asp.net core中修改HttpContext.Request.Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42701311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com