TheWebGuy
TheWebGuy

Reputation: 12595

ASP.NET Core OWIN Middleware

I have an ASP.NET Core app and a simple OWIN middleware to check some data. But I'd like to only run the middleware when a page is requested. Right now its running when assets are requested as well such as images, css, etc.

How can I make the owin middleware code only execute on page requests?

Registration:

app.UseSiteThemer();

Site Themer extension class:

public static class SiteThemerExtensions
{
    public static IApplicationBuilder UseSiteThemer(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<SiteThemerMiddleware>();
    }
}

OWIN Middleware:

public class SiteThemerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ISiteService _siteService;

    public SiteThemerMiddleware(RequestDelegate next, ISiteService siteService)
    {
        _siteService = siteService;
        _next = next;
        //_logger = loggerFactory.CreateLogger<SiteThemerMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        await Task.Run(() =>
         {

             Console.Write("OWIN Hit");
         });


        //_logger.LogInformation("Handling request: " + context.Request.Path);
        await _next.Invoke(context);
        //_logger.LogInformation("Finished handling request.");
    }
}

Upvotes: 2

Views: 893

Answers (1)

tpeczek
tpeczek

Reputation: 24125

There are two aspects of ASP.NET Core pipeline you can use for you goal here: ordering and branching.

The rules around ordering are very simple - the order in which middlewares are added is the order in which they are going to be executed. This means that if middleware like yours is placed after some middleware which can end the pipeline (for example static files) it will not be invoked if it happens.

In order to branch the pipeline you can use Map or MapWhen methods. The first branches the pipeline based on path while the other based on predicate. Middlewares added with Map or MapWhen will be invoked only if the branch condition is met.

You can read more details about the pipeline here

Upvotes: 2

Related Questions