从 WebAPI 生成到 MVC 控制器操作的路由 URL [英] Generating Route Url to MVC controller action from WebAPI

查看:29
本文介绍了从 WebAPI 生成到 MVC 控制器操作的路由 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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,我将如何去做?

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?

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

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.

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

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?

推荐答案

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

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

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

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

这篇关于从 WebAPI 生成到 MVC 控制器操作的路由 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆