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".

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,573 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,494 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
338 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jerry Fu - MSFT 741 Reputation points Microsoft Vendor
    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.