ASP.NET Core controller level exception handling

To handle exceptions on Controller/Action level Exception Filters are used.

[TypeFilter(typeof(SampleExceptionFilter))]
public class ExceptionController : Controller

Exception Filters are implemented using IExceptionFilter with OnExcetion method override to handle exceptions.

Exception Filters can be applied to Controller and Action level.

Further read:

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-7.0#exception-filters

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.filters.iexceptionfilter?view=aspnetcore-7.0

Middleware in OWIN

There are 2 ways of writing OWIN middleware in ASP.NET Core.

  • Pure OWIN – usefull if you want to integrate with OWIN compatible module but not written in C#
  • ASP.NET Core OWIN middleware

ASP.NET Core Middleware:

This type of middleware can be:

  • delegate of Func<HttpContext, Func<Task>, Task>
  • class with IMiddleware imlementation
app.Use(async (context, next) =>
{
    // Do work that can write to the Response.
    await next.Invoke();
    // Do logging or other work that doesn't write to the Response.
});

Pure OWIN Middleware:

This rather would be used to integrate with OWIN middlewares written in different language, so that ASP.NET Core implementation directly is not possible.

  • delegate of type Func<IDictionary<string, object>, Task>
  • must set keys of owin.ResposeBody and owin.ResponseHeaders

usage in ASP.NET Core pipeline:

public void Configure(IApplicationBuilder app)
{
    app.UseOwin(pipeline =>
    {
        pipeline(next => DelegateTask);
    });
}

Further read:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/owin?view=aspnetcore-6.0

Owin model and Kestrell request handling

  • OWIN – Open Web Interface for .NET
  • allows web apps to be decoupled from web servers
  • defines standard way for middleware to be used in a pipeline to handle requests and provide responses
  • ASP.NET Core applications can interoperate with OWIN-based applications, servers and middleware

Microsoft.AspNetCore.Owin package provides two adapter implementations:

  • ASP.NET Core to OWIN
  • OWIN to ASP.NET Core

This allows ASP.NET Core to be hosted on top of an OWIN compatible server/host or for other OWIN compatible components to be run on top of ASP.NET Core.

Further read:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/owin?view=aspnetcore-6.0