我有全局属性,我需要知道区域,控制器和动作。由于路由(内部区域注册和属性路由),我无法使用RawUrl。我遵循了以下两种方法,但在这两种方法中,我的区域都是空的。当我使用路线然后我得到区域名称就好了。当我执行redirecttoaction或url.action或手动输入网址等时,为什么我的区域为空?我们正在使用MVC 5.0。
var routingValues = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)).Values;
var currentArea = (string) routingValues["area"] ?? string.Empty;
var currentController = (string) routingValues["controller"] ?? string.Empty;
var currentAction = (string) routingValues["action"] ?? string.Empty;
var handler = HttpContext.Current.Handler as System.Web.Mvc.MvcHandler;
var area = handler.RequestContext.RouteData.Values["area"];
var controller = handler.RequestContext.RouteData.Values["controller"];
var action = handler.RequestContext.RouteData.Values["action"];
就像我上面所说,如果我使用路线(/ TipHotLine),那么我得到的区域名称就好了。
public class AgencyAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Agency";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Agency_default",
"Agency/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"tiphotline",
"tiphotline",
new
{
controller = "tiphotline",
action = "Index",
Area = "Agency"
}
);
}
}
答案 0 :(得分:4)
注册区域时,使用的MapRoute方法是向每个路径添加dataContextToken。您可以查看源代码here,您将看到如下方法,您会注意到添加数据令牌的行:
public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces)
{
...
route.DataTokens[RouteDataTokenKeys.Area] = AreaName;
...
return route;
}
因此,在您的过滤器中,您只需要使用键"area"
而不是路由值来获取数据令牌。例如,以下过滤器将添加在路径
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var routingValues = filterContext.RouteData.Values;
var currentArea = filterContext.RouteData.DataTokens["area"] ?? string.Empty;
var currentController = (string)routingValues["controller"] ?? string.Empty;
var currentAction = (string)routingValues["action"] ?? string.Empty;
filterContext.HttpContext.Response.AddHeader("Routing info", string.Format("controller={0},action={1},area={2}", currentController, currentAction, currentArea));
}