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?
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.
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).
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 .
IApplicationBuilder An object that provides the mechanisms to configure an application's request pipeline.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With