capiono
capiono

Reputation: 2997

Get Route Data in class

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?

Upvotes: 3

Views: 4880

Answers (2)

Muflix
Muflix

Reputation: 6798

I found solution here https://github.com/aspnet/Mvc/issues/3826

string parameter = "action" // or controller
_httpContextAccessor.HttpContext.GetRouteValue(parameter);

Upvotes: 4

Technetium
Technetium

Reputation: 6188

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"];

Upvotes: 1

Related Questions