Dr Schizo
Dr Schizo

Reputation: 4386

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?

Upvotes: 6

Views: 3136

Answers (2)

MichaelMao
MichaelMao

Reputation: 2806

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);
        }
    }

Upvotes: 2

PercivalMcGullicuddy
PercivalMcGullicuddy

Reputation: 5553

It should be possible by creating your own exception filter.

namespace MyApplication.Filters
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Filters;

    public class CustomHeadersFilterAttribute : ExceptionFilterAttribute 
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            context.Response.Content.Headers.Add("X-CustomHeader", "whatever...");
        }
    }

}

http://www.asp.net/web-api/overview/error-handling/exception-handling

Upvotes: 0

Related Questions