cha*_*q45 11 .net c# asp.net asp.net-mvc asp.net-core-middleware
我正在尝试读取从客户端发送到我的后端的请求正文。内容以 JSON 格式发送,并由用户从表单输入。如何在为控制器路由设置的中间件中读取请求正文。
这是我的模型
namespace ChatboxApi.Models
{
public class User
{
public string Login { get; set; } = default;
public string Password { get; set; } = default;
public string Email { get; set; } = default;
public string FullName { get; set; } = default;
public int Phone { get; set; } = default;
public string Website { get; set; } = default;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器
namespace ChatboxApi.Controllers
{
[ApiController]
[Route("api/signup")]
public class SignupController : ControllerBase
{
[HttpPost]
public ActionResult SignUp([FromBody] User user)
{
return Ok(user);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的中间件类
namespace ChatboxApi.Middleware
{
public class CreateSession
{
private readonly RequestDelegate _next;
public CreateSession(RequestDelegate next)
{
this._next = next;
}
public async Task Invoke(HttpContext httpContext)
{
//I want to get the request body here and if possible
//map it to my user model and use the user model here.
}
}
Run Code Online (Sandbox Code Playgroud)
Ren*_*ena 30
通常Request.Body
不支持倒带,因此只能读取一次。一个临时解决方法是在调用后立即拉出主体EnableBuffering
,然后将流倒回至 0 并且不处置它:
public class CreateSession
{
private readonly RequestDelegate _next;
public CreateSession(RequestDelegate next)
{
this._next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var request = httpContext.Request;
if (request.Method == HttpMethods.Post && request.ContentLength > 0)
{
request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
//get body string here...
var requestContent = Encoding.UTF8.GetString(buffer);
request.Body.Position = 0; //rewinding the stream to 0
}
await _next(httpContext);
}
}
Run Code Online (Sandbox Code Playgroud)
注册服务:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseHttpsRedirection();
app.UseMiddleware<CreateSession>();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23138 次 |
最近记录: |