获取行动完整URL的ASP.NET MVC完整、行动、URL、MVC

2023-09-02 20:44:59 作者:作业,我要勒死你

有没有得到一个动作的完整URL的一个内置的方式吗?

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

我在寻找类似 GetFullUrl(行动,控制器),将返回类似 HTTP://www.fred .COM /控制器/动作

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

我要寻找这样做的原因是为了避免硬编码在生成这样的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("Posts", "Edit", new { id = 5 }, this.Request.Url.Scheme);

HtmlHelper的(@Html)也有,你可以使用剃刀来创建一个锚元素ActionLink的方法的重载,但它也需要在主机名和片段参数。所以,我只是选择使用@ 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>
 
精彩推荐
图片推荐