通过一个中间件解决ASP.Net Core中Request.Body为空的问题

    在ASP.Net Core的机制中,当接收到http的头为 application/x-www-form-urlencoded 或者 multipart/form-data 时,netcore会通过 FormReader 预先解析 Request.Body 的 Form 的内容,经过 Reader 读取后 Request.Body 就会变 null,这样我们在代码中需要再次使用 Request.Body 时就会报空异常。

详见代码:https://github.com/aspnet/HttpAbstractions/blob/release/2.0/src/Microsoft.AspNetCore.Http/Features/FormFeature.cs

如果需要在代码中再次使用 Request.Body 是数据流时,就必须开启 Request 的 Rewind 模式,这里提供了一个中间件去开启

using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;

namespace Microsoft.AspNetCore.Http
{
    public class EnableRequestRewindMiddleware
    {
        private readonly RequestDelegate _next;

        public EnableRequestRewindMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Request.EnableRewind();
            await _next(context);
        }
    }

    public static class EnableRequestRewindExtension
    {
        public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<EnableRequestRewindMiddleware>();
        }
    }
}

在 Startup.cs 的 Configure 方法引用中间件即可

//引入EnableRequestRewind中间件
app.UseEnableRequestRewind(); 

另外,这个中间件已经作为 Senparc.Weixin.MP.MvcExtension 的一个组件提供,使用 Senparc Weixin SDK 的直接引入即可

https://github.com/JeffreySu/WeiXinMPSDK/pull/1131

不允许评论