有没有一种内置的方法来获取一个动作的完整URL?
我正在寻找像GetFullUrl("Action", "Controller")这样的东西,它会返回像http://www.fred.com/Controller/Action这样的东西。
我这样做的原因是为了避免在自动生成的电子邮件中硬编码URL,这样URL就可以始终相对于网站的当前位置生成。
发布于 2010-01-05 18:37:28
有一个Url.Action重载,它接受你想要的协议(例如http,https)作为参数-如果你指定了它,你会得到一个完全限定的URL。
下面是一个在action方法中使用当前请求的协议的示例:
var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);razor (@Html)也有一个ActionLink方法的重载,您可以在HtmlHelper中使用它来创建锚元素,但它也需要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>发布于 2011-07-22 07:19:25
正如帕迪提到的:如果您使用显式指定要使用的协议的 UrlHelper.Action() URL的重载,则生成的将是绝对的和完全限定的,而不是相对的。
我写了一篇名为How to build absolute action URLs using the UrlHelper class的博客文章,其中我建议出于可读性的考虑编写一个自定义扩展方法:
/// <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")发布于 2017-01-31 17:07:49
这就是你需要做的。
@Url.Action(action,controller, null, Request.Url.Scheme)https://stackoverflow.com/questions/2005367
复制相似问题