Sample of my request
http://localhost:8065/api/note
POST
content-type:application/json
request body: { \"id\" : \"1234\", \"title\" : \"test\", \"status\" : \"dr
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)