Serlok
Serlok

Reputation: 462

When exception thrown, CORS is lost

I am using ASP.NET Web API, after throwing exception, I am able to catch it in GlobalExceptionHandler, but I get CORS error and can't enter App_error. I tried multiple solutions, nothing is working, right now I have this flow.

Custom Exception is thrown in controller, then we enter GlobalExceptionHandler:

public class GlobalExceptionHandler : IExceptionHandler
{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        ExceptionDispatchInfo.Capture(context.Exception).Throw();
        return Task.CompletedTask;
    }
}

And it is not going further, I get CORS on front.

Any solution?

Upvotes: 0

Views: 342

Answers (2)

Serlok
Serlok

Reputation: 462

I managed to resolve problem by doing everything inside lifter, so App_error is not used anymore

public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly Logger m_Logger = LogManager.GetCurrentClassLogger();
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        var exception = context.Exception;
        var statusCode = HttpStatusCode.InternalServerError;

        if (exception != null)
        {
            var errorMessage = exception.Message;
            if (exception is BaseException be)
            {
                statusCode = be.StatusCode;
            }
            m_Logger.Error(exception, context.Request.RequestUri.AbsoluteUri);
            var response = context.Request.CreateResponse(statusCode, new { errorMessage });
            context.Result = new ResponseMessageResult(response);
        }

        return Task.CompletedTask;
    }
}

Upvotes: 0

Paresh
Paresh

Reputation: 993

You could do something like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
namespace Web.API.Handler
{
    public class ErrorHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {

            context.Result = new TextPlainErrorResult()
            {
                Request = context.ExceptionContext.Request,
                Content = "Oops! Sorry! Something went wrong." + "Please contact support so we can try to fix it."
            };
        }

        private class TextPlainErrorResult : IHttpActionResult
        {
            public HttpRequestMessage Request { get; set; }

            public string Content { get; set; }

            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, Content);
                //CORS Support
                if (!response.Headers.Contains("Access-Control-Allow-Origin"))
                    response.Headers.Add("Access-Control-Allow-Origin", "*");


                return Task.FromResult(response);
            }
        }
    }

}

Upvotes: 1

Related Questions