Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp MVC Action link absolute url

Tags:

c#

asp.net-mvc

I have a set of views that display to specific users. These are views I've copied from other views in our app, and changed them slightly.

In these views I'm using Html.Action link, but I need these to return an absolute url instead of the relative. I know there are extra parameters that can be used to get this effect, but I dont tihnk its viable to change all my links in all my views.

Ideally I'de like to make a change in one place and have all my links render as required. Surely there must be something I can set, or a function I can override to accomplish this.

like image 275
user466859 Avatar asked Oct 05 '10 13:10

user466859


2 Answers

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I present a custom extension method named AbsoluteAction. I encourage you to check it out!

/// <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);
}

ASP.NET MVC includes built-in functionality for the generation of absolute URLs, though not in a very intuitive way.

There are several overloads of UrlHelper.Action() method that enable you to pass additional parameters like route values, the protocol to use and the host name for the URL. If you are using any overload that allows you to specify the protocol parameter, the generated URL will be absolute. Thus, the following code can be used to generate an absolute URL for the About action method of the HomeController:

@Url.Action("About", "Home", null, "http")
like image 128
Marius Schulz Avatar answered Nov 05 '22 10:11

Marius Schulz


You can create a new extension method called Html.AbsoluteAction. AbsoluteAction can add the extra parameters necessary to make the URL absolute, so you only have to write that code once, in your custom extension method.

like image 44
Dave Swersky Avatar answered Nov 05 '22 11:11

Dave Swersky