在课堂上获取路线数据 [英] Get Route Data in class
问题描述
在MVC 5中,您可以从
In MVC 5 you can get RouteData from
HttpContext.Current.Request.RequestContext.RouteData
在MVC 6中,我要获取RouteData,必须从以下位置访问它:
In MVC 6, I want to get the RouteData, I have to access it from:
IHttpContextAccessor httpContextAccessor
但是它没有Route Dictionary属性.
But it doesn't have the Route Dictionary Property.
我如何在MVC 6中做到这一点?
How do I do this in MVC 6?
推荐答案
可以在任何过滤器,尽管在Items集合上="nofollow noreferrer"> HttpContext
(很方便,也可以在过滤器的*Context
对象上使用),以供其他代码在调用管道中使用.
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.
这里是一个通过 ResourceExecutingContext
noreferrer> 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();
}
}
现在,在过滤器之后运行的任何代码中,您现在都可以通过 IHttpContextAccessor
像这样:
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"];
这篇关于在课堂上获取路线数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!