I'm running Asp.Net Core v2.2 and I'm trying to implement response caching middleware which should be controlled by action attributes so that it would be possible to granularly control caching behavior like caching time, keys, etc. The caching middleware should run after response formatters so that it will cache the data in the format it will go to response.
I'd like to get access to action metadata inside of middleware before action executes so that middleware can decide whether to pull data from cache or continue execution.
As an alternative the desired caching functionality can be done as Mvc Filter where all information about action is available. The only drawback is that the response formatting needs to be added there as well and it feels like reinventing the wheel.
Sounds like a problem for... endpoint routing! Maybe 馃槃
cc @JamesNK @rynowak
Endpoint routing will enable this feature. In ASP.NET Core 2.2 the matching of a route to an action doesn't happen until the MVC middleware runs (this will change in 3.0).
Do you only need access to the attributes after MVC has run? If so then you might be able to get it from the matched endpoint.
// This helper method comes in 3.0. For now you'll need a copy in your app
public static Endpoint GetEndpoint(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<IEndpointFeature>()?.Endpoint;
}
var endpoint = GetEndpoint(context);
// Endpoint will be null if the URL didn't match an action, e.g. a 404 response
if (endpoint != null)
{
var yourAttribute = endpoint.Metadata.GetMetadata<YourAttributeOnTheMvcAction>();
}
The end goal is to be able to avoid running MVC part if the data for request is present in the cache so it should run before MVC. But looks like it will be possible to achieve only starting from v3. Thank you for clarifications and also for sample code to achieve that in v3.
Most helpful comment
Endpoint routing will enable this feature. In ASP.NET Core 2.2 the matching of a route to an action doesn't happen until the MVC middleware runs (this will change in 3.0).
Do you only need access to the attributes after MVC has run? If so then you might be able to get it from the matched endpoint.