2012-04-09 121 views
1

是否可以使用自定義路由處理代碼?
例如客戶端請求服務器http://server.com/api/v1/json/profile/和我的代碼調用ApiController,MyAction動作參數version=1,format=json,action=profile自定義路由管理

回答

1

這樣的事情?您必須使用不同的參數名稱才能執行操作,因此您不會與控制器操作發生衝突。

.MapRoute("name", "api/v{version}/{format}/{_action}", new { controller = "ApiController", action = "MyAction" }); 

編輯國產版工作,你想要的方式。

+0

你的意思是'MapRoute'? – 2012-04-09 13:13:38

+0

是的:)對不起 - 這就是你從頭頂開始做的事情。 – Brendan 2012-04-09 13:14:44

1

我會先將「action」參數重命名爲別的東西,否則路由會變得非常混亂(也許稱它爲目的?)。另外,我相信像下面將工作:

routes.MapRoute(
    // name of your route 
    "MyRoute", 

    // route template 
    "api/v{version}/{format}/{purpose}", 

    // default route values 
    new { 
     controller = "ApiController", 
     action = "MyAction", 
    }, 

    // constraints placed on parameters (make sure they are valid) 
    new { 
     version = @"^\d+$",   // number only (can also include decimals) 
     format = @"^(json|text|xml)$", // if you want filtering... 
    } 
); 

然後:

public ApiController : Controller 
{ 
    public ActionResult MyAction(Int32 version, String format, String purpose) 
    { 
    throw new NotImplementedException(); 
    } 
}