2017-03-09 303 views
3

我有一个HttpContext.Request对象,它有错误的表单中的数据,我想修复它并发送正确的HttpContext。 HttpContext.Request.Form是只读的,但如果不是,我会简单地完成以下操作; HttpContext.Request.Form [“a”] =“一个正确的值”;如何修改asp.net核心中的HttpContext.Request.Form

所以,管道中最好的地方在哪里做这件事。 是否有可能通过反射使HttpContext.Request.Form可写入可访问?

+0

你是什么意思?“发送正确的HttpContext的方式?”你是否将它传递给另一个方法/对象,或者你是否试图将它发送回客户端? – greenjaed

+0

我正在拦截传入的请求并修复中间件中的不良表单数据,并将良好的表单数据发送到未处理流水线的其余部分。 –

回答

4

这比我想象的容易。我在我的中间件是有纠正进来状态不佳的数据这样做。

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对象不是这样让我更换整个表格。

+0

我没有'AsNameValueCollection'扩展方法!它在哪里? –

+0

AsNameValueCollection位于IdentityServer4.dll内部,我发布了下面的源代码。 –

1

AsNameValueCollection位于IdentityServer4.dll内部。

public static class IReadableStringCollectionExtensions 
{ 
    [DebuggerStepThrough] 
    public static NameValueCollection AsNameValueCollection(this IDictionary<string, StringValues> collection) 
    { 
     NameValueCollection values = new NameValueCollection(); 
     foreach (KeyValuePair<string, StringValues> pair in collection) 
     { 
      string introduced3 = pair.get_Key(); 
      values.Add(introduced3, Enumerable.First<string>(pair.get_Value())); 
     } 
     return values; 
    } 

    [DebuggerStepThrough] 
    public static NameValueCollection AsNameValueCollection(this IEnumerable<KeyValuePair<string, StringValues>> collection) 
    { 
     NameValueCollection values = new NameValueCollection(); 
     foreach (KeyValuePair<string, StringValues> pair in collection) 
     { 
      string introduced3 = pair.get_Key(); 
      values.Add(introduced3, Enumerable.First<string>(pair.get_Value())); 
     } 
     return values; 
    } 
}