ASP.NET MVC - 如何获取动作的完整路径

dev*_*per 36 asp.net-mvc asp.net-mvc-routing

在视图内部,我可以获取动作的完整路线信息吗?

如果我在控制器MyController中有一个名为DoThis的动作.我可以走一条路"/MyController/DoThis/"吗?

Dar*_*rov 79

你的意思是在Url助手上使用Action方法:

<%= Url.Action("DoThis", "MyController") %>
Run Code Online (Sandbox Code Playgroud)

或在剃刀:

@Url.Action("DoThis", "MyController")
Run Code Online (Sandbox Code Playgroud)

这会给你一个相对url(/MyController/DoThis).

如果你想得到一个绝对的url(http://localhost:8385/MyController/DoThis):

<%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %>
Run Code Online (Sandbox Code Playgroud)


Mar*_*ulz 9

几天前,我写了一篇关于这个主题的博客文章(请参阅如何使用UrlHelper类构建绝对操作URL).正如Darin Dimitrov所说:UrlHelper.Action如果protocol明确指定参数,将生成绝对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("SomeAction", "SomeController")