In the ASP 5 aka core all configuration from former MVC 5 global.asax goes into new root Startup.cs file.
So In startup.cs file in Configure Method
simple write
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
app.UseExceptionHandler( options => { options.Run( async context => { String contextPath = context.Request.Path.Value; //api request if (contextPath.Contains("/api") && contextPath != "/") { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "text/html"; var ex = context.Features.Get<IExceptionHandlerFeature>(); //if (ex != null) //{ var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace }"; await context.Response.WriteAsync(err).ConfigureAwait(false); // } } //Route request else { context.Response.Redirect("/home/about"); await Task.FromResult<object>(null); } }); } ); |
If it is api request then error will be shown like html or return to default error page we have made for exception handling
or you can use your own Exception handling middle ware
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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 HandleExceptionAsync(context, ex); } } private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { if (exception == null) return; var code = HttpStatusCode.InternalServerError; String message=String.Empty; //if (exception is MyNotFoundException) code = HttpStatusCode.NotFound; if (exception.Message == @"IDX10803: Unable to obtain configuration from: 'http://localhost:54540/.well-known/openid-configuration'.") { code = HttpStatusCode.Unauthorized; message = "Unauthorized"; } else { message = exception.Message; } //else if (exception is MyException) code = HttpStatusCode.BadRequest; await WriteExceptionAsync(context, exception, code,message).ConfigureAwait(false); } private static async Task WriteExceptionAsync(HttpContext context, Exception exception, HttpStatusCode code,String message) { var response = context.Response; response.ContentType = "application/json"; response.StatusCode = (int)code; await response.WriteAsync(JsonConvert.SerializeObject(new { error = new { message = message, exception = exception.GetType().Name, InnerException = exception.InnerException!=null?exception.InnerException.Message:"", StatusCode=code, Source = exception.Source, // type=exception.GetType(), StackTrace = exception.StackTrace } })).ConfigureAwait(false); } } |
and startup.cs->Configure
1 |
app.UseMiddleware(typeof(ErrorHandlingMiddleware)); |