Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API global error handling add custom header in response

I was wondering if it was possible to set some custom header values whenever an internal server error has occurred? I am currently doing:

public class FooExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        // context.Result already contains my custom header values
        context.Result = new InternalServerErrorResult(context.Request);
    }
}

Here I also want to set some header values but though it appears in the request the response does not contain it.

Is there a way of doing this?

like image 849
Dr Schizo Avatar asked Jul 27 '15 12:07

Dr Schizo


People also ask

How do I add a header to API response?

Adding Custom Header for Individual Response We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response object through the HttpContext object. Then, we add a new header, with the name of x-my-custom-header and a value of individual response .

How do I register an exception filter globally in Web API?

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration. Configuration. Filters collection. Exception filters in this collection apply to any Web API controller action.

How do you handle global exception?

When using the Global Exception Handler with a project that includes a Try Catch, make sure to group activities into a Sequence inside the Try container. Otherwise, the Global Exception Handler does not execute. In the case of nested activities, the Global Exception Handler executes for each activity in the call stack.


1 Answers

There is a sample code for your reference, my ApiExceptionHandler is your FooExceptionHandler

    public class ApiExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            var response = new Response<string>
            {
                Code = StatusCode.Exception,
                Message = $@"{context.Exception.Message},{context.Exception.StackTrace}"
            };

            context.Result = new CustomeErrorResult
            {
                Request = context.ExceptionContext.Request,
                Content = JsonConvert.SerializeObject(response),                
            };
        }
    }

    internal class CustomeErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response =
                new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(Content),
                    RequestMessage = Request
                };

            response.Headers.Add("Access-Control-Allow-Origin", "*");
            response.Headers.Add("Access-Control-Allow-Headers", "*");

            return Task.FromResult(response);
        }
    }
like image 92
MichaelMao Avatar answered Nov 13 '22 08:11

MichaelMao