在 ASP.NET MVC 中获取操作的完整 URL [英] Getting full URL of action in ASP.NET MVC

查看:33
本文介绍了在 ASP.NET MVC 中获取操作的完整 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有获取操作完整 URL 的内置方法?

Is there a built-in way of getting the full URL of an action?

我正在寻找类似 GetFullUrl("Action", "Controller") 的东西,它会返回类似 http://www.fred.com/Controller/Action.

I am looking for something like GetFullUrl("Action", "Controller") that would return something like http://www.fred.com/Controller/Action.

我寻找这个的原因是为了避免在生成的自动电子邮件中硬编码 URL,以便始终可以相对于站点的当前位置生成 URL.

The reason I am looking for this is to avoid hardcoding URLs in automated emails that are generated so that the URLs can always be generated relative to the current location of the site.

推荐答案

有一个 Url.Action 的重载,它将你想要的协议(例如 http、https)作为参数 - 如果你指定了这个,你会得到一个完全合格的网址.

There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.

这是一个在动作方法中使用当前请求的协议的例子:

Here's an example that uses the protocol of the current request in an action method:

var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);

HtmlHelper (@Html) 也有一个 ActionLink 方法的重载,你可以在 razor 中使用它来创建一个锚元素,但它也需要 hostName 和 fragment 参数.所以我只是选择再次使用@Url.Action:

HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:

<span>
  Copy
  <a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a> 
  and post it anywhere on the internet!
</span>

这篇关于在 ASP.NET MVC 中获取操作的完整 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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