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)
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)
归档时间: |
|
查看次数: |
252298 次 |
最近记录: |