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