-
I am using I want to be able to allow all routes except All the examples I've come across seem to show how to configure this with controllers using code or attributes when I want to do it entirely in the I tried using a regex.
I am by no means a regex expert and am not even sure this is the way to go about this so thinking there must be a cleaner way to achieve this. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Looks like I found what I want in https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0#regular-expressions-in-constraints |
Beta Was this translation helpful? Give feedback.
-
Rather than have ugly regex paths inside configuration files. I added a middleware to ignore specific routes. I quite like having the public class IgnoredRouteMiddleware
{
readonly RequestDelegate _next;
readonly IgnoredRouteOptions _options;
public IgnoredRouteMiddleware(RequestDelegate next, IgnoredRouteOptions options) =>
(_next, _options) = (next, options);
public async Task Invoke(HttpContext context)
{
if (_options.Routes.Any(route =>
context.Request.Path.HasValue &&
context.Request.Path.StartsWithSegments(route, StringComparison.OrdinalIgnoreCase)))
{
context.Response.StatusCode = (int)_options.HttpStatusCode;
return;
}
await _next.Invoke(context).ConfigureAwait(false);
}
}
public class IgnoredRouteOptions
{
public IEnumerable<string> Routes { get; set; }
public HttpStatusCode HttpStatusCode { get; set; }
} in "IgnoredRoutes": {
"Routes": [
"/health",
"/log",
"/metrics",
"/status"
],
"HttpStatusCode": "Forbidden"
} |
Beta Was this translation helpful? Give feedback.
Rather than have ugly regex paths inside configuration files. I added a middleware to ignore specific routes. I quite like having the
"Path": "{**catch-all}"
with a catch all to ignore certain paths. If there is a nicer way I would be very interested to know but for the moment this appears to do the job it needs to.