开发者

ASP.NET MVC - how to get a full path to an action

开发者 https://www.devze.com 2023-03-21 22:43 出处:网络
Inside o开发者_JAVA技巧f 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/\"? You

Inside o开发者_JAVA技巧f 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/"?


You mean like using the Action method on the Url helper:

<%= Url.Action("DoThis", "MyController") %>

or in Razor:

@Url.Action("DoThis", "MyController")

which will give you a relative url (/MyController/DoThis).

And if you wanted to get an absolute url (http://localhost:8385/MyController/DoThis):

<%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %>


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.Action will generate absolute URLs if the protocol parameter is specified explicitly.

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")

0

精彩评论

暂无评论...
验证码 换一张
取 消