Is there any way to get request body in .NET Core FilterAttribute?

后端 未结 4 1529
暗喜
暗喜 2021-02-08 23:26

Sample of my request

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


        
4条回答
  •  悲&欢浪女
    2021-02-08 23:51

        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(requestBody);
                    var _myService = (IMyService)context.HttpContext.RequestServices.GetService(typeof(IMyService));
                        if (!hasAccess)
                        {
                            context.Result = new UnauthorizedObjectResult(_errorMessage);
                        }
                }
        
                private async Task 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- use your filter

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

提交回复
热议问题