asp.net-mvc 从 WebAPI 生成到 MVC 控制器操作的路由 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15250186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:37:26  来源:igfitidea点击:

Generating Route Url to MVC controller action from WebAPI

asp.net-mvcasp.net-mvc-4asp.net-web-apiasp.net-mvc-routingurlhelper

提问by Kramer00

I'm used to generating route URLs to other controller actions within an MVC controller action using something similar to below:

我习惯于使用类似于下面的内容在 MVC 控制器操作中生成到其他控制器操作的路由 URL:

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

    public ActionResult Index2( string other)
    {
    }
}

But I also need to be able to generate URLs to MVC controller actions from within webapi too, How would I go about doing this?

但是我还需要能够从 webapi 中生成到 MVC 控制器操作的 URL,我将如何去做?

There seems to be a UrlHelper property on the APIController but I cant find any examples of how to use this and have not been able to figure it out myself.

APIController 上似乎有一个 UrlHelper 属性,但我找不到有关如何使用它的任何示例,并且我自己也无法弄清楚。

UPDATE : The reason I am trying to generate a url is that this particular webapi method sends an email which provides the recipient with a link to direct the user back to an appropriate section of the site. I obviously want to get away from hardcoding this as it will not work for different deployments and also if I begin changing the routing this link will be broken. Is there a better approach to doing this?

更新:我尝试生成 url 的原因是这个特定的 webapi 方法发送了一封电子邮件,该电子邮件为收件人提供了一个链接,以将用户引导回站点的适当部分。我显然想摆脱硬编码,因为它不适用于不同的部署,而且如果我开始更改路由,此链接将被破坏。有没有更好的方法来做到这一点?

回答by RaghuRam Nadiminti

You can use MVC route names as well with web API UrlHelper. Example,

您也可以将 MVC 路由名称与 Web API UrlHelper 一起使用。例子,

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

or

或者

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