asp.net-mvcasp.net-core.net-coreasp.net-core-webapicustom-action-filter

How can I read the Request Body in a .Net 5 Webapi project using an Action Filter


Using .Net 5 WebApi, I have an action filter and I am attempting to simply read the body of a request but when I read request.body, the body is always empty.

How can I read the text of the body of the request OnActionExecuting (e.g. Debug.Write(body)) and have it not be empty?

MyCustomFilter:

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);
    }
}

My Api Controller:

[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();
    }
}

Startup.cs

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

SomeData Object

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

The Json I am posting

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

Solution

  • The model can be directly obtained in the action filter as shown below.

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

    Test result: enter image description here