asp.net-mvc ASP.NET MVC - 如何获取操作的完整路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6783365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC - how to get a full path to an action
提问by dev.e.loper
Inside of a View can I get a full route information to an action?
在视图内部,我可以获得操作的完整路线信息吗?
If I have an action called DoThis in a controller MyController. Can I get to a path of "/MyController/DoThis/"?
如果我在控制器 MyController 中有一个名为 DoThis 的操作。我可以到达 的路径"/MyController/DoThis/"吗?
回答by Darin Dimitrov
You mean like using the Actionmethod on the Url helper:
您的意思是在 Url 助手上使用Action方法:
<%= Url.Action("DoThis", "MyController") %>
or in Razor:
或在剃刀:
@Url.Action("DoThis", "MyController")
which will give you a relative url (/MyController/DoThis).
这会给你一个相对的 url ( /MyController/DoThis)。
And if you wanted to get an absolute url (http://localhost:8385/MyController/DoThis):
如果您想获得绝对网址 ( http://localhost:8385/MyController/DoThis):
<%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %>
回答by Marius Schulz
Some days ago, I wrote a blog post about that very topic (see How to build absolute action URLs using the UrlHelper class). As Darin Dimitrov mentioned: UrlHelper.Actionwill generate absolute URLs if the protocolparameter is specified explicitly.
几天前,我写了一篇关于该主题的博客文章(请参阅如何使用 UrlHelper 类构建绝对操作 URL)。正如 Darin Dimitrov 提到的:UrlHelper.Action如果protocol明确指定参数,将生成绝对 URL 。
However, I suggest to write a custom extension method for the sake of readability:
但是,为了可读性,我建议编写一个自定义扩展方法:
/// <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);
}
The method can then be called like this: @Url.AbsoluteAction("SomeAction", "SomeController")
然后可以像这样调用该方法: @Url.AbsoluteAction("SomeAction", "SomeController")

