有没有办法在.NET Core FilterAttribute中获取请求体?

时间:2017-08-04 06:34:01

标签: c# asp.net-core asp.net-core-mvc .net-core

我的请求样本

http://localhost:8065/api/note
POST
content-type:application/json
request body: { "id" : "1234", "title" : "test", "status" : "draft"}

,响应应为

{ "msg" : "ok", "code" : 1}

行动

public async Task<IActionResult> Post([FromBody]NoteModel model)

为了自动记录每个请求,我创建了一个属性来完成这项工作。该属性如下所示:(来自Microsoft Docs

public class SampleActionFilterAttribute : TypeFilterAttribute
{
    public SampleActionFilterAttribute():base(typeof(SampleActionFilterImpl))
    {
    }

    private class SampleActionFilterImpl : IActionFilter
    {
        private readonly ILogger _logger;
        public SampleActionFilterImpl(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<SampleActionFilterAttribute>();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            _logger.LogDebug("[path]" + context.HttpContext.Request.Path);
            _logger.LogDebug("[method]" + context.HttpContext.Request.Method);
            _logger.LogDebug("[body]"); //log request body, expectation: { "id" : "1234", "title" : "test", "status" : "draft"}
            _logger.LogDebug("[statuscode]" + context.HttpContext.Response.StatusCode);
            _logger.LogDebug("[response]"); //log response
        }
    }
}

我尝试使用streamReader来获取请求主体只获取空字符串。

StreamReader reader = new StreamReader(context.HttpContext.Request.Body);
string text = reader.ReadToEnd();

是因为[fromBody]从控制器读取了正文,所以流不能被读取两次?如果是这样,我应该如何在OnActionExecuted方法中获取请求正文和响应?

更新

我刚刚将Set的代码复制到我的项目中,而不是工作。这是调试gif enter image description here

4 个答案:

答案 0 :(得分:5)

相应于此&#34; Best way to log/read request body in a middleware&#34;线程,以下应该工作:

window.initializeCodeFolding("show" === "show")

Read request body twice SO post

中描述的类似方法

更新window.initializeCodeFolding("show" === "hide")中的上述方法将在中间件中使用,而不是在操作过滤器中使用。不同之处在于,当操作过滤器正在调用时(即使是// using Microsoft.AspNetCore.Http.Internal; public class SampleActionFilterAttribute : TypeFilterAttribute { ... public void OnActionExecuting(ActionExecutedContext context) { // read body before MVC action execution string bodyData = ReadBodyAsString(context.HttpContext.Request); } private string ReadBodyAsString(HttpRequest request) { var initialBody = request.Body; // Workaround try { request.EnableRewind(); using (StreamReader reader = new StreamReader(request.Body)) { string text = reader.ReadToEnd(); return text; } } finally { // Workaround so MVC action will be able to read body as well request.Body = initialBody; } return string.Empty; } } ),已经读取了正文流并且已填充ReadBodyAsString

好的nesw就是这样,因此可以使用OnActionExecuting直接在动作过滤器中获取模型。在你的情况下:

[FromBody] model

答案 1 :(得分:1)

以下代码段对我有用,仅在出现任何异常时才记录请求。(。Net Core 3.1)

{

public class ExceptionFilter : IActionFilter
{
    private ConcurrentDictionary<string, string> requests = new ConcurrentDictionary<string, string>();

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Exception != null)

        {
            StringBuilder parameters = new StringBuilder();

            _logger.LogError("Error while executing action:" + context.ActionDescriptor.DisplayName);

            string errRequest;
            if(requests.TryGetValue(context.HttpContext.TraceIdentifier,out errRequest))
            {
                _logger.LogError(errRequest);
            }

            _logger.LogError(context.Exception);

            context.Result = new ObjectResult("Error!!!")
            {
                StatusCode = 500,
            };
            context.ExceptionHandled = true;
        }

        string req;
            requests.Remove(context.HttpContext.TraceIdentifier, out req);


    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var arg in context.ActionArguments)
        {

            sb.Append(arg.Key.ToString() + ":" + Newtonsoft.Json.JsonConvert.SerializeObject(arg.Value) + "\n");

        }
        requests.TryAdd(context.HttpContext.TraceIdentifier, sb.ToString());
    }


}

}

答案 2 :(得分:0)

如果您在控制器中使用IActionResult并且想要.NET对象,则可以编写如下过滤器:

public class SampleFilter : IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult)
        {
            var objResult = (ObjectResult)context.Result;
        }
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {

    }
}

到达OnActionExecuted时,ObjectResult任务已经完成,因此您只需提取值即可。您还可以使用objResult.StatusCode获取StatusCode。

在控制器中,返回Ok(...)实际创建一个OkObjectResult等。

如果您特别想要序列化结果,则Set的答案更有效。

答案 3 :(得分:0)

    in .net core 3.1, I usually use this approach to handle this scenario
    
    1- Create Async Filter Attribute
    
    public class MyFilter : IAsyncAuthorizationFilter
        {
            private string _errorMessage = UserAccessErrorMessages.NO_ACCESS;
            public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
            {
                string requestBody = await ReadBodyAsString(context.HttpContext.Request);
                var reportFiltration = JsonConvert.DeserializeObject<YourModel>(requestBody);
                var _myService = (IMyService)context.HttpContext.RequestServices.GetService(typeof(IMyService));
                    if (!hasAccess)
                    {
                        context.Result = new UnauthorizedObjectResult(_errorMessage);
                    }
            }
    
            private async Task<string> ReadBodyAsString(Microsoft.AspNetCore.Http.HttpRequest request)
            {
                var initialBody = request.Body; // Workaround
    
                try
                {
                    //request.EnableRewind();
    
                    using (StreamReader reader = new StreamReader(request.Body))
                    {
                        string text = await reader.ReadToEndAsync();
                        return text;
                    }
                }
                finally
                {
                    // Workaround so MVC action will be able to read body as well
                    request.Body = initialBody;
                }
            }
        }
2- Create Your Custom Attribute
public class MyAttribute : TypeFilterAttribute, IAllowAnonymous
    {
        public MyAttribute () : base(typeof(MyFilter))
        {

        }
    }

3- 使用过滤器

    [HttpPost]
    [ActionName("MyAction")]
    [MyAttribute]
    public async Task<IActionResult> PostData([FromBody]MyModel model)