Get Route Data in class

本秂侑毒 提交于 2019-12-10 22:09:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!