在课堂上获取路线数据 [英] Get Route Data in class

查看:66
本文介绍了在课堂上获取路线数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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();
    }

}

现在,在过滤器之后运行的任何代码中,您现在都可以通过

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆