I am trying to write a middleware that only applies to Razor pages that don't have the [AllowAnonymous]
attribute on the Model class. However to achieve this, I'd have to somehow figure out the type of the Page Model from the middleware through a HttpContext
object. I'm not sure if this type information even exists, because the middlewares run before the Razor Page does, so maybe the endpoint isn't resolved from the path yet.
I've tried peeking inside the context.Features.Get<IEndpointFeature>()?.Endpoint
class, but I haven't been able to find any useful information regarding the endpoint's type.
I have also considered Filters, but I am modifying an existing project that implements many checks with Middlewares, and I'd like to avoid rewriting them to IActionFilter
s if I can.
You can use Middleware like below:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (context, next) =>
{
var endpoint = context.GetEndpoint();
//endpoint declares with AllowAnonymous attribute
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() is object)
{
//do your stuff...
}
await next.Invoke();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});