如何读取JSON主体,然后将其转换为ASP.NET Core WebAPI中的C#控制器类?

pnwntuvh  于 12个月前  发布在  .NET
关注(0)|答案(2)|浏览(114)

有这个简单的端点:

[HttpPost]
public async Task<IActionResult> CreateUser([FromBody] UserInput userInput)
{
    if (userInput == null) return BadRequest();
    var userOutput = await _userService.AddUser(userInput);
    return CreatedAtRoute("GetUser", new { userId = userOutput.UserId }, userOutput);
}

字符串
我如何检索已发送的确切JSON?
就像现在一样,json输入中的所有字段都必须在UserInput类中实现。我想知道是否还有一种方法可以在转换为UserInput类之前捕获原始主体。
多谢帮忙!

yqlxgs2m

yqlxgs2m1#

获取实际的JSON体当您在. NET 5或更高版本中使用Model Binding时,
首先,将此扩展方法添加到您的解决方案中,使我们的生活更轻松

public static async Task<string> GetRawBodyAsync(
    this HttpRequest request,
    Encoding encoding = null)
{
    if (!request.Body.CanSeek)
    {
        // We only do this if the stream isn't *already* seekable,
        // as EnableBuffering will create a new stream instance
        // each time it's called
        request.EnableBuffering();
    }

    request.Body.Position = 0;

    var reader = new StreamReader(request.Body, encoding ?? Encoding.UTF8);

    var body = await reader.ReadToEndAsync().ConfigureAwait(false);

    request.Body.Position = 0;

    return body;
}

字符串
我们需要在Map控制器/端点之前在管道中添加小型中间件,以使此方法正确工作

app.Use(next => context => {
    context.Request.EnableBuffering();
    return next(context);
});


现在,您可以在Action中获取JSON Body请求,如下所示

[HttpPost]
 public async Task<IActionResult> CreateUser([FromBody] UserInput userInput)
 {
     string rawRequestBody = await Request.GetRawBodyAsync(); //<<< get your json as string

     if (userInput == null) return BadRequest();
     var userOutput = await _userService.AddUser(userInput);
     return CreatedAtRoute("GetUser", new { userId = userOutput.UserId }, userOutput);
 }


更多信息请参见Reading the raw request body as a string in ASP.NET Core

mznpcxlj

mznpcxlj2#

您可以使用HttpLogging中间件来捕获此请求信息
HTTP Logging是一个中间件,记录有关传入HTTP请求和HTTP响应的信息。HTTP Logging提供以下日志:
HTTP请求信息通用属性标头正文HTTP响应信息
很容易配置和设置,你可以添加任何请求头,响应头等日志

builder.Services.AddHttpLogging(logging =>
{
    logging.LoggingFields = HttpLoggingFields.All;
    logging.RequestHeaders.Add("sec-ch-ua");
    logging.ResponseHeaders.Add("MyResponseHeader");
    logging.MediaTypeOptions.AddText("application/javascript");
    logging.RequestBodyLogLimit = 4096;
    logging.ResponseBodyLogLimit = 4096;

});

字符串
通过在Program.cs中调用以下命令将其添加到管道中:
app.UseHttpLogging();
并将其添加到appsettings.json中的logLevel中,
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"

相关问题