问题
In MVC 5 you can get RouteData from
HttpContext.Current.Request.RequestContext.RouteData
In MVC 6, I want to get the RouteData, I have to access it from:
IHttpContextAccessor httpContextAccessor
But it doesn't have the Route Dictionary Property.
How do I do this in MVC 6?
回答1:
It can be extracted within any Filter, though it probably makes the most sense in a ResourceFilter. All of the various filters' *Context
objects inherit from the same ActionContext which has the RouteData
property you're looking for. From there, you can copy it on to the Items
collection on the HttpContext (conveniently, also available on the filter's *Context
object) for use in other code further down the invocation pipeline.
Here is an example that extracts it via the ResourceExecutingContext in a ResourceFilter.
public class ExtractRouteValueResourceFilter : IAsyncResourceFilter {
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) {
var value = context.RouteData.Values["key"];
if (value != null) {
context.HttpContext.Items["key"] = value;
}
await next();
}
}
In any code that runs after your filter, you could now access the route value via the IHttpContextAccessor like so:
var routeValue = accessor.HttpContext.Items["key"];
回答2:
I found solution here https://github.com/aspnet/Mvc/issues/3826
string parameter = "action" // or controller
_httpContextAccessor.HttpContext.GetRouteValue(parameter);
来源:https://stackoverflow.com/questions/45470425/get-route-data-in-class