获取ASP.NET MVC中的完整操作URL

Ala*_*ark 364 .net c# asp.net-mvc url-routing

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

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

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

Pad*_*ddy 566

Url.Action过载会将您所需的协议(例如http,https)作为参数 - 如果您指定此参数,则会获得完全限定的URL.

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

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

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>
Run Code Online (Sandbox Code Playgroud)

  • 在MVC6中,我这样做了`<a href="@Url.Action("Login","Account",null,Context.Request.Scheme)">登录</a> (11认同)
  • 没有麻烦 - 你认为应该有更好的方法来做到这一点,但嘿...... (6认同)
  • @fiberOptics - 对你来说相当晚,但对于其他人:你遇到的问题是你在非标准端口上运行Azure模拟器(通常在开始时会有关于它的注释),就像这样的端口这项工作是必需的.在生产中,它应该使用标准端口(443),因此它不会包含在URL中. (2认同)

Mar*_*ulz 133

正如Paddy所提到的:如果您使用UrlHelper.Action()明确指定要使用的协议的重载,则生成的URL将是绝对且完全限定的而不是相对的.

我写了一篇名为" 如何使用UrlHelper类构建绝对操作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);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在视图中使用它:

@Url.AbsoluteAction("Action", "Controller")
Run Code Online (Sandbox Code Playgroud)

  • 我要添加(或修改)的唯一方法是用HttpContext.Current.Request.Url.Scheme替换文字"http".这将允许在适当时使用https. (9认同)
  • 这很棒.谢谢.小注意......方法名称"ActionAbsolute"是VS自动完成的更好选择,因为Url.Action()将在Url.ActionAbsolute()旁边. (2认同)