访问当前RouteContext [英] Access the current RouteContext

查看:363
本文介绍了访问当前RouteContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC 5我可以访问的HttpContext 使用 HttpContext.Current 。什么是访问的HttpContext 或更好的,只有电流 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?

推荐答案

首先 RouteContext 是不是你要访问的对象。它是唯一使用,如果路线被andled信号,并且因此内的MVC不流动。你可能想访问的RouteData 而不是

First RouteContext is not an object you want to access. It is uniquely used to signal if the route was andled, and thus does not flow within MVC. You probably want to access RouteData instead.

下面的一些方法来访问它。

Here as a few ways to access it:

在一个控制器可以访问 - this.ActionContext.RouteData 或为HttpContext.Current相当于这一点。 ActionContext.HttpContext 或直接 this.HttpContext

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

ActionFilter 您可以通过访问它们的上下文中传递:

in an ActionFilter you can access them through the passed in context:

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



在别的地方,你必须访问DI系统(比如一个服务,或者构造函数时,你必须到服务提供商的直接访问),你可以得到当前请求的 ActionContext中但请注意,这只有当您在你得到了在被限制在请求中传递的要求和你的ServiceProvider的范围

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;
}



更新注意:随着Beta3中和 IContextAccessor< T> ; 改为 IScopedInstance< T>

请注意:您也可以只写自己的存取,如果你想它只是一个简单的类与被注册为作用域的服务的get / set属性。

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.

这篇关于访问当前RouteContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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