Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
lisburnite Avatar asked Jan 27 '20 10:01

lisburnite


People also ask

What is app UseStaticFiles () in .NET Core?

UseStaticFiles() method adds StaticFiles middleware into the request pipeline. The UseStaticFiles is an extension method included in the StaticFiles middleware so that we can easily configure it. Now, open the browser and send http request http://localhost:<port>/default.html which will display default.

How do I serve a static file in NET Core?

To serve static files from an ASP.NET Core app, you must configure static files middleware. With static files middleware configured, an ASP.NET Core app will serve all files located in a certain folder (typically /wwwroot).

How do I access Wwwroot files?

in the wwwroot folder as shown below. You can access static files with base URL and file name. For example, we can access above app. css file in the css folder by http://localhost:<port>/css/app.css .

What is IApplicationBuilder in .NET Core?

IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.


1 Answers

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

like image 103
Riccardo Bassilichi Avatar answered Oct 12 '22 23:10

Riccardo Bassilichi