2011-06-15 106 views
1
string actionName = "Users"; 

[HttpGet] 
[ActionName(actionName)] 
public ActionResult GetMe() 
{ 

} 

...給出了:一個對象引用需要非靜態字段,方法或屬性是否可以在運行時動態指定動作名稱?

這只是一個測試,雖然,有沒有辦法做到這一點?如果是這樣,我可以重新使用相同的控制器,並可能在運行中創建新的URI ...對嗎?

回答

5

假設你有如下控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 
} 

你可以寫一個自定義的路由處理:

public class MyRouteHander : IRouteHandler 
{ 
    public IHttpHandler GetHttpHandler(RequestContext requestContext) 
    { 
     var rd = requestContext.RouteData; 
     var action = rd.GetRequiredString("action"); 
     var controller = rd.GetRequiredString("controller"); 
     if (string.Equals(action, "users", StringComparison.OrdinalIgnoreCase) && 
      string.Equals(controller, "home", StringComparison.OrdinalIgnoreCase)) 
     { 
      // The action name is dynamic 
      string actionName = "Index"; 
      requestContext.RouteData.Values["action"] = actionName; 
     } 
     return new MvcHandler(requestContext); 
    } 
} 

最後,在你的路由定義的自定義路由處理程序相關聯:

routes.MapRoute(
    "Default", 
    "{controller}/{action}/{id}", 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
).RouteHandler = new MyRouteHander(); 

現在如果您要求/home/users這是將被提供的Home控制器的10個動作。

0

您可以在另一個路由參數中執行switch語句。

+1

如果我做了一個switch語句並不意味着我需要事先知道這些URI嗎? – BigOmega 2011-06-15 18:23:52

+0

還不完全。您有控制器手動處理路由。 – 2011-06-15 18:40:16

相關問題