21

MVC控制器動作我已經習慣了使用類似於下面的東西產生的MVC控制器動作中路由指向其他控制器操作:生成路由地址從的WebAPI

public class ApplicationController : Controller 
{ 
    public ActionResult Index() 
    { 
     var url = Url.RouteUrl("routename", 
      new { controller = "Application", Action = "Index2" , other="other" }); 
    } 

    public ActionResult Index2(string other) 
    { 
    } 
} 

但我也需要能夠從webapi內部生成到MVC控制器操作的URL,我將如何去做這件事?

APIController似乎有一個UrlHelper屬性,但我無法找到如何使用它的任何示例,並且無法自己弄清楚它。

更新: 我試圖生成一個網址的原因是,這個特定的webapi方法發送一封電子郵件,爲收件人提供一個鏈接,指導用戶回到網站的相應部分。我顯然希望擺脫硬編碼,因爲它不適用於不同的部署,並且如果我開始更改路由,這個鏈接將被打破。有沒有更好的方法來做到這一點?

回答

27

您可以使用MVC路由名稱以及Web API UrlHelper。例如,

Url.Link("Default", new { Controller = "Account", Action = "Login" }); 

Url.Route("Default", new { Controller = "Account", Action = "Login" }); 
+0

你是正確的。謝謝 – Kramer00 2013-03-11 11:32:46

+0

@TrueBlueAussie你正在看錯UrlHelper。看看http一個不是mvc的。 – Steve 2014-02-12 18:58:27

+1

http://msdn.microsoft.com/en-us/library/system.web.http.routing.urlhelper_methods(v=vs.118).aspx。如果您正在使用屬性路由,請命名您的路由。 – Steve 2014-02-12 19:04:07