How to return error response?

Anonymous
2023-09-12T19:02:50.5866667+00:00

When i aims to call first action method with the accept header is "text/xml".

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET ASP.NET API
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-09-13T03:30:31.73+00:00

    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.

    User's image


    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.