【问题标题】:When exception thrown, CORS is lost抛出异常时,CORS 丢失
【发布时间】:2020-09-27 08:13:31
【问题描述】:

我正在使用 ASP.NET Web API,在抛出异常后,我可以在 GlobalExceptionHandler 中捕获它,但是我收到 CORS 错误并且无法输入 App_error。我尝试了多种解决方案,但没有任何效果,现在我有这个流程。

控制器抛出自定义异常,然后我们输入GlobalExceptionHandler:

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

而且它不会更进一步,我在前面得到了 CORS。

有什么办法吗?

【问题讨论】:

    标签: asp.net exception asp.net-web-api cors


    【解决方案1】:

    你可以这样做

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

    }

    【讨论】:

    • 我做了类似的事情
    【解决方案2】:

    我设法通过在 Lifter 内完成所有操作来解决问题,因此不再使用 App_error

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

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 2013-04-04
      • 2013-05-24
      • 2015-01-29
      • 1970-01-01
      • 2022-01-18
      • 2019-02-28
      • 1970-01-01
      相关资源
      最近更新 更多