Friday, March 23, 2018

Response.TrySkipIisCustomErrors equivalent for asp.net core?

Leave a Comment

How to prevent IIS from overriding custom error pages with IIS default error pages? Is there a Response.TrySkipIisCustomErrors equivalent for asp.net core? In ASP Net MVC I use the code below to send error without a custom page but in asp net core it is not working.

try {     // some code } catch (Exception ex) {     Response.TrySkipIisCustomErrors = true;     Response.StatusCode = (int)HttpStatusCode.InternalServerError;     mensagem = ex.Message; } 

1 Answers

Answers 1

What you can try is writing an exception handling middleware. Here is a blog post which I have used for reference. Something along the lines of

    public class ErrorHandlingMiddleware     {       private readonly RequestDelegate next;        public ErrorHandlingMiddleware(RequestDelegate next)       {         this.next = next;       }        public async Task Invoke(HttpContext context)       {         try         {             await next(context);         }         catch (Exception ex)         {             await CustomHandleExceptionAsync(context, ex);         }       }      private static Task CustomHandleExceptionAsync(HttpContext context, Exception exception)     {          if (exception is NotFoundException)         {           var customJson = JsonConvert.SerializeObject(new{ error =           exception.Message });          context.Response.ContentType = "application/json";          context.Response.StatusCode = (int)HttpStatusCode.NotFound;          return context.Response.WriteAsync(customJson);        }    } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment