Hi, ActionFilterAttribute is able to achieve this.
You could refence this sample.
public class MyfilterAttribute : ActionFilterAttribute
{
private readonly string[] _acceptTypes;
public MyfilterAttribute(params string[] acceptTypes)
{
_acceptTypes = acceptTypes;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var headers = filterContext.HttpContext.Request.Headers;
var acceptHeaderValues = headers.ContainsKey("Accept") ? headers["Accept"] : new StringValues();
if (!(acceptHeaderValues.Any() && _acceptTypes.Any(d => acceptHeaderValues.Contains(d))))
{
filterContext.Result = new JsonResult(new { Error = "An error message here" }) { StatusCode = 415 };
}
}
}
Then add [Myfilter("text/csv")]
to your action, it will return your custom response.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.