marcus
marcus

Reputation: 10086

Access the current RouteContext

In MVC 5 I you can access HttpContext using HttpContext.Current. What is the preferred way of accessing the HttpContext or better, only the current RouteContext?

Upvotes: 4

Views: 2845

Answers (1)

Yishai Galatzer
Yishai Galatzer

Reputation: 8862

RouteContext is not an object you typically want to access. It is used by MVC to signal if the route was handled, and thus does not flow. You probably want to access RouteData instead.

Here as a few ways to access it:

On a controller you can access - this.ActionContext.RouteData or for the HttpContext.Current equivalent this.ActionContext.HttpContext or directly this.HttpContext

in an ActionFilter you can access them through the method parameter:

public void OnActionExecuting(ActionExecutingContext context)
{
    var routeData = context.RouteData;
    var httpContext = context.HttpContext;
    ...
}

Anywhere else where you have access to the DI system (say constructor of a service, or when you have direct access to the service provider) you can get at the current request's ActionContext but note that this works only when you are within a scope of the request and your serviceprovider you got passed in is scoped to the request.

public MyService(IScopedInstance<ActionContext> contextAccessor)
{
    _httpContext = contextAccessor.Value.HttpContext;
    _routeData = contextAccessor.Value.RouteData;
}

Note: You can also just write your own "Accessor" if you'd like it is just a simple class with a get/set property that gets registered as a Scoped service.

Upvotes: 5

Related Questions