Search code examples
asp.net-coremiddleware

Detect static file request from .NET core middleware


I'm writing some middleware to parse the sub-domain of a given request URL to determine the website theme. I want to ignore static file requests in order to reduce unnecessary database lookups, and I'm wondering if there's a cleaner way to do it.

This is what I've tried so far:

var staticFileExtensions = new List<string> { ".css", ".js", ".png", ".ico" };
if (staticFileExtensions.Any(x => httpContext.Request.Path.Value.EndsWith(x)))
{
    await _next(httpContext);
}
else
{
    var hostParts = httpContext.Request.Host.Host.Split('.').ToList();
    if (httpContext.Request.Path.StartsWithSegments(new PathString("/healthcheck"))
    || (hostParts.Count == 6 && _whitelistedDomains.Contains(hostParts[0])))
    {
        httpContext.Items.Add("account", hostParts[0]);
        await _next(httpContext);
    }
    else
    {
        httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
    }
}

This is where I've added it to Startup.cs:

app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseDomainWhitelisting();

It feels as though there should be a cleaner way to detect which requests to ignore, or maybe I'm missing something?


Solution

  • You can use conditional middleware based on request. Something like:

    app.UseMiddlewareOne();
    
    app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
    {
        appBuilder.UseMiddlewareTwo();
    });
    
    app.UseMiddlewareThree();
    

    Source: https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core