.Net Core: Return IActionResult from a custom Exception Middleware

asp.net core exception handling middleware
asp.net core return error message
asp.net core return internal server error with message
asp net core 3 exception handling middleware
asp.net core exception logging middleware
net core exception handling best practices
asp.net core 400 bad request
.net core return status code with message

I have created a new Exception middleware in my .Net Core application. All the exceptions throughout the application are captured and logged here. What I want is to return a IActionResult type like InternalServerError() or NotFound() from the Exception Middleware and not do response.WriteAsync as below.

Controller Method:

   public async Task<IActionResult> Post()
        //Do Something
        return Ok();


public class ExceptionMiddleware
        private readonly RequestDelegate _next;
        public ExceptionMiddleware(RequestDelegate next)
            _next = next;

        public async Task Invoke(HttpContext context)
                await _next.Invoke(context);
            catch (Exception ex)
                await HandleExceptionAsync(context, ex);

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
            var response = context.Response;
            var statusCode = (int)HttpStatusCode.InternalServerError;
            var message = exception.Message;
            var description = exception.Message;

            response.ContentType = "application/json";
            response.StatusCode = statusCode;

            await response.WriteAsync(JsonConvert.SerializeObject(new ErrorResponse
                Message = message,
                Description = description

IActionResult is a thing from MVC, so it is only available within the MVC pipeline (including Razor Pages). Just before the MVC middleware terminates, it will execute those action results using ExecuteAsync. That method is then responsible of writing that response to HttpContext.Response.

So in custom middleware, you cannot just set an action result and have it executed, since you are not running within the MVC pipeline. However, with that knowledge, you can simply execute the result yourself.

Let’s say you want to execute a NotFoundResult which is what Controller.NotFound() creates. So you create that result and call ExecuteAsync with an . That executor will be able to execute that result object and write to the response:

var result = new NotFoundResult();
await result.ExecuteAsync(new ActionContext
    HttpContext = context,

Handle errors in ASP.NET Core web APIs, Creating a custom ErrorHandlerMiddleware function The end result for a Razor Pages app is that the Error.cshtml Razor Page is returned whenever an exception occurs in NET Core will catch the exception in its infrastructure, log it, and return a [Route("/error-local-development")] public IActionResult� To see the result of the exception handling lambda in the sample app, use the ProdEnvironment and ErrorHandlerLambda preprocessor directives, and select Trigger an exception on the home page. UseStatusCodePages. By default, an ASP.NET Core app doesn't provide a status code page for HTTP status codes, such as 404 - Not Found. The app returns a

What you're trying to do can be done by simply adding this line:

app.UseStatusCodePagesWithReExecute("/Public/Error", "?statusCode={0}");

to the Configure method in the Startup.cs. Then you can create your Public Controller with Error method that does the following:

public IActionResult Error(int? statusCode = null)
    // Retrieve error information in case of internal errors.
    var error = HttpContext.Features.Get<IExceptionHandlerFeature>()?.Error;
    var path = HttpContext.Features.Get<IExceptionHandlerPathFeature>()?.Path;

    // TODO: Redirect here based on your status code or perhaps just render different views for different status codes.

There is also another middleware that allows you to do a similar thing:

app.UseStatusCodePages(async context =>
    if (context.HttpContext.Response.StatusCode == 401)
    else if (context.HttpContext.Response.StatusCode == 500)
        // TODO: Redirect for 500 and so on...

Handle errors in ASP.NET Core, To tackle this problem we will use Custom Exception Handling with Middlewares. 5. 6. [AllowAnonymous]. public IActionResult Error(). {. return View(new� public IActionResult ContentResult() { return Content("Here's the ContentResult message."); } Summary. The Action Result classes in ASP.NET Core MVC provide a significant chunk of the functionality you'll be using in your controllers. They return status codes, objects, files, other content, and even redirect the client.

That's not really possible due to where IActionResult and middleware sit in relation to one another in the architecture. Middleware sits much lower, and so it can't reach further up the stack to IActionResult. Here's an answer that talks more about it: https://stackoverflow.com/a/43111292/12431728

Creating a custom ErrorHandlerMiddleware function, NET Core Web API projects and how these approaches differ from MVC error handling. public async Task<IActionResult> GetProduct(GetProductRequest request) another action to deal with the status code and return a custom response. Handling the Exception with Custom Code. There are legitimate reasons that you want to handle all exception that is not caught in the business logic. For this purpose, you can use a custom exception handler and registrate it as a middleware. This exception handler below differentiates between development and production environments.

Custom Exception Handling in .Net Core with a Middleware , NET Core API using only the latest and greatest technologies. public IActionResult Get() the status code and the content type of our response, logged the error message, and finally returned the response with the custom created object. Exception Handling Middleware can also provide more detailed content-negotiated output in the local development environment. Use the following steps to produce a consistent payload format across development and production environments: In Startup.Configure, register environment-specific Exception Handling Middleware instances:

Handling errors in ASP.NET Core Web API, NET Core Catch Model Binding Exceptions, I explained how you can use ApiBehaviorOptions… public IActionResult LogDoNavigate([FromBody] MyModel model). {. try STEP 1: CREATE A CUSTOM MIDDLEWARE. This middleware will catch errors and return the exception as a JSON result object. Alternatively, if you just want to return an arbitrary status code and aren't concerned with the Exception-based approach, you can use return new HttpStatusCodeResult(400); Update: as of .NET Core RC 2, the Http prefix is dropped.

Global Error Handling in ASP.NET Core Web API, NET Core middlewares is much lower concept in the layering than all MVC stuff cases for error handling while we need to return views and json from middlewares. TODO: stay tuned throw; } } }. For registing middleware it's common to Like mentioned return View(“404”); where View — is IActionResult � This means that even though you can technically (there would be no exception thrown for that) change the status code on the response, or inject some headers into it using a custom middleware that runs at the end of the pipeline, that would have no effect on the response anymore, as it is simply too late.