如何在ASP.NET Core 3.0中间件中从HttpContext.Request
中读取字符串形式的主体值?
private static void MyMiddleware(IApplicationBuilder app)
{
app.Run(async ctx =>
{
var body = ctx.Request.??????
await context.Response.WriteAsync(body);
});
}
答案 0 :(得分:1)
有两种自定义中间件的方法,如下所示:
1。第一种方法是您可以在Startup.cs中编写中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.Run(async ctx =>
{
string body;
using (var streamReader = new System.IO.StreamReader(ctx.Request.Body, System.Text.Encoding.UTF8))
{
body = await streamReader.ReadToEndAsync();
}
await ctx.Response.WriteAsync(body);
});
//...
}
2。第二种方法是您可以自定义如下的中间件类:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
string body;
using (var streamReader = new System.IO.StreamReader(httpContext.Request.Body, System.Text.Encoding.UTF8))
{
body = await streamReader.ReadToEndAsync();
}
await httpContext.Response.WriteAsync(body);
}
}
然后您需要在Startup.cs中注册:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseMiddleware<MyMiddleware>();
//...
}