2011-07-28 111 views
2

我正在編寫一個ActionFilter並需要從ActionExecutingContext參數(我想實現基於快速和基於登錄的安全性)獲取區域名稱。可能嗎?從ActionExecutingContext獲取區域名稱

+2

*可能* [ASP.NET MVC的重複 - 獲取當前區域名稱中查看或控制器](http://stackoverflow.com/questions/27236 89/asp-net-mvc-get-current-area-name-in-view-or-controller) – bzlm

回答

2

從MVC源代碼:

static string GetAreaName(RouteBase route) 
    { 
     var area = route as IRouteWithArea; 
     if (area != null) 
     { 
      return area.Area; 
     } 
     var route2 = route as Route; 
     if ((route2 != null) && (route2.DataTokens != null)) 
     { 
      return (route2.DataTokens["area"] as string); 
     } 
     return null; 
    } 


    static string GetAreaName(RouteData routeData) 
    { 
     object obj2; 
     if (routeData.DataTokens.TryGetValue("area", out obj2)) 
     { 
      return (obj2 as string); 
     } 
     return GetAreaName(routeData.Route); 
    } 
+0

不幸的是這些方法在內部類中:) – SiberianGuy

+0

但是MVC期貨中有類似的公共類 – SiberianGuy

0

使用

@Html.Controller(); 
@Html.Action(); 
@Html.Id(); 
@Html.Area(); 

代碼

public static class HtmlRequestHelper 
{ 
    public static string Id(this HtmlHelper htmlHelper) 
    { 
     var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values; 

     if (routeValues.ContainsKey("id")) 
      return (string)routeValues["id"]; 
     else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id")) 
      return HttpContext.Current.Request.QueryString["id"]; 

     return string.Empty; 
    } 

    public static string Controller(this HtmlHelper htmlHelper) 
    { 
     var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values; 

     if (routeValues.ContainsKey("controller")) 
      return (string)routeValues["controller"]; 

     return string.Empty; 
    } 

    public static string Action(this HtmlHelper htmlHelper) 
    { 
     var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values; 

     if (routeValues.ContainsKey("action")) 
      return (string)routeValues["action"]; 

     return string.Empty; 
    } 

    public static string Area(this HtmlHelper htmlHelper) 
    { 
     var dataTokens = HttpContext.Current.Request.RequestContext.RouteData.DataTokens; 

     if (dataTokens.ContainsKey("area")) 
      return (string)dataTokens["area"]; 

     return string.Empty; 
    } 
}