Disable *all* exception handling in ASP.NET Web API 2 (to make room for my own)?

前端 未结 5 2026
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 12:21

I want to wire up exception handling in a middleware component, something like this:

public override async Task Invoke(IOwinContext context)
{
    try
    {
         


        
5条回答
  •  温柔的废话
    2020-12-02 13:07

    Not sure if this will work for you, but I have a similar requirement to send all errors back as JSON even for not found errors. I created a base controller and overrode the ExecuteAsync allowing me to create my own responses.

    public class ControllerBase : ApiController
    {
        protected string ClassName = "ControllerBase::";
    
        public override System.Threading.Tasks.Task ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)
        {
            try
            {
                System.Threading.Tasks.Task TaskList = base.ExecuteAsync(controllerContext, cancellationToken);
    
                if (TaskList.Exception != null && TaskList.Exception.GetBaseException() != null)
                {
                    JSONErrorResponse AsyncError = new JSONErrorResponse();
                    AsyncError.ExceptionMessage = TaskList.Exception.GetBaseException().Message;
                    AsyncError.ErrorMessage = string.Format("Unknown error {0} ExecuteAsync {1}", ClassName ,controllerContext.Request.RequestUri.AbsolutePath);
                    AsyncError.HttpErrorCode = HttpStatusCode.BadRequest;
    
                    HttpResponseMessage ErrorResponse = controllerContext.Request.CreateResponse(AsyncError.HttpErrorCode, AsyncError);
    
                    return System.Threading.Tasks.Task.Run(() => ErrorResponse);
                }
                return TaskList;
            }
            catch (Exception Error)
            {
                JSONErrorResponse BadParameters = new JSONErrorResponse();
                BadParameters.ExceptionMessage = Error.Message;
                BadParameters.ErrorMessage = string.Format("Method [{0}], or URL [{1}] not found, verify your request", controllerContext.Request.Method.Method, controllerContext.Request.RequestUri.AbsolutePath);
                BadParameters.HttpErrorCode = HttpStatusCode.NotFound;
                HttpResponseMessage ErrorResponse = controllerContext.Request.CreateResponse(BadParameters.HttpErrorCode, BadParameters);
    
                return System.Threading.Tasks.Task.Run(() => ErrorResponse);
            }
        }
    }
    
    public class JSONErrorResponse
    {
        //Possible message from exception
        public string ExceptionMessage { get; set; }
        //Possible custom error message
        public string ErrorMessage { get; set; }
        //Http error code
        public HttpStatusCode HttpErrorCode { get; set; }
    }
    

提交回复
热议问题