0

使用 .Net 5 WebApi,我有一个动作过滤器,我试图简单地读取请求的正文,但是当我读取 request.body 时,正文总是空的。

如何读取请求 OnActionExecuting 的正文文本(例如 Debug.Write(body))并使其不为空?

我的自定义过滤器:

public class MyCustomFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Do something before the action executes.
        Debug.Write(MethodBase.GetCurrentMethod(), context.HttpContext.Request.Path);

        var bodyStream = context.HttpContext.Request.BodyReader.AsStream(true);

        using (var reader = new StreamReader(bodyStream))
        {
            var body = reader.ReadToEnd();

            Debug.Write(body);
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
        Debug.Write(MethodBase.GetCurrentMethod(), context.HttpContext.Request.Path);
    }
}

我的 API 控制器:

[ServiceFilter(typeof(MyCustomFilter))]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    public IEnumerable<WeatherForecast> Post([FromBody] SomeData someData)
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

启动.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddScoped<MyCustomFilter>();
    }

SomeData 对象

public class SomeData
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我发布的 Json

{
  "id": 1,
  "name": "test thing"
}
4

1 回答 1

1

模型可以直接在action filter中得到,如下图。

public void OnActionExecuting(ActionExecutingContext context)
    {
        var body = context.ActionArguments["someData"] as SomeData ;
    }

测试结果: 在此处输入图像描述

于 2021-02-06T03:00:51.057 回答