如何在ASP.NET MVC中查找动作的绝对URL?是否有内置的方式来获取完整的网址?
我正在寻找像GetFullUrl(""Action"", ""Controller"")那样会返回类似的东西http://www.fred.com/Controller/Action。
我正在寻找这个的原因是为了避免在自动生成的电子邮件中对网址进行硬编码,以便始终可以根据网站的当前位置生成网址。
如果使用明确指定要使用的协议的UrlHelper.Action()的重载,则生成的URL将是绝对的并且是完全限定的,而不是相对的。
我建议编写自定义扩展方法:
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
那么你可以简单地在你的视图中使用它:
@Url.AbsoluteAction("Action", "Controller")
Url.Action有一个重载,它将所需的协议(例如http,https)作为参数 - 如果指定了此参数,则会获得完全限定的URL。
以下是一个在操作方法中使用当前请求协议的示例:
var fullUrl = this.Url.Action(""Edit"", ""Posts"", new { id = 5 }, this.Request.Url.Scheme);
HtmlHelper(@Html)也有一个ActionLink方法的重载,您可以在razor中使用该方法创建一个锚元素,但是它也需要hostName和fragment参数。所以我只是选择再次使用@ Url.Action:
<span>
Copy
<a href='@Url.Action(""About"", ""Home"", null, Request.Url.Scheme)'>this link</a>
and post it anywhere on the internet!
</span>