Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何使用操作过滤器读取.NET5WebAPI项目中的请求正文_Asp.net Mvc_Asp.net Core_.net Core_Asp.net Core Webapi_Custom Action Filter - Fatal编程技术网

Asp.net mvc 如何使用操作过滤器读取.NET5WebAPI项目中的请求正文

Asp.net mvc 如何使用操作过滤器读取.NET5WebAPI项目中的请求正文,asp.net-mvc,asp.net-core,.net-core,asp.net-core-webapi,custom-action-filter,Asp.net Mvc,Asp.net Core,.net Core,Asp.net Core Webapi,Custom Action Filter,使用.Net 5 WebApi,我有一个操作过滤器,我试图简单地读取请求的正文,但当我读取request.body时,正文总是空的 如何读取OnActionExecuting请求的正文(例如Debug.Write(body))并使其不为空 MyCustomFilter: public class MyCustomFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context)

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

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

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);
    }
}
我的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();
    }
}
我发布的Json

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

模型可直接在动作过滤器中获得,如下所示

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

简短回答:你不能(或者更确切地说:你不应该这样做)。您不应该在
IActionFilter
中读取请求正文,因为如果在
IActionFilter
中读取请求流,则会阻止应用程序的其余部分读取请求正文,除非将其复制到新的缓冲区,如果您不小心,您的应用程序很容易因过度使用内存而遭到拒绝服务。而是使用中间件。这是真的。。。而且确实是正确的答案。谢谢由于我无法将评论标记为正确答案,并且我的目标是获得传入的模型,因此我将删除@Yinqiu,但感谢你们两位的回答。请问您为什么使用
[ServiceFilter(typeof(MyCustomFilter))]
?您没有在操作筛选器中使用DI,它允许稍后在操作本身中再次读取它吗?
{
  "id": 1,
  "name": "test thing"
}
public void OnActionExecuting(ActionExecutingContext context)
    {
        var body = context.ActionArguments["someData"] as SomeData ;
    }