Getting Full Url of Action in ASP.NET MVC

Getting full URL of action in ASP.NET MVC

There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.

Here's an example that uses the protocol of the current request in an action method:

var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);

HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:

<span>
Copy
<a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a>
and post it anywhere on the internet!
</span>

How do I find the absolute url of an action in ASP.NET MVC?

Click here for more information, but esentially there is no need for extension methods. It's already baked in, just not in a very intuitive way.

Url.Action("Action", null, null, Request.Url.Scheme);

Getting Absolute URL from an ASP.NET MVC Action

You can do it by the following:

var urlBuilder =
new System.UriBuilder(Request.Url.AbsoluteUri)
{
Path = Url.Action("Action", "Controller"),
Query = null,
};

Uri uri = urlBuilder.Uri;
string url = urlBuilder.ToString();
// or urlBuilder.Uri.ToString()

Instead of Url.Action() in this sample, you can also use Url.Content(), or any routing method, or really just pass a path.

But if the URL does go to a Controller Action, there is a more compact way:

var contactUsUriString =
Url.Action("Contact-Us", "About",
routeValues: null /* specify if needed */,
protocol: Request.Url.Scheme /* This is the trick */);

The trick here is that once you specify the protocol/scheme when calling any routing method, you get an absolute URL. I recommend this one when possible, but you also have the more generic way in the first example in case you need it.

I have blogged about it in details here:

http://gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/

Extracted from Meligy’s AngularJS & Web Dev Goodies Newsletter

How to get FULL URL in ASP.NET Core Razor Pages?

You can use the UriHelper extension methods GetDisplayUrl() or GetEncodedUrl() to get the full URL from the request.

GetDisplayUrl()

Returns the combined components of the
request URL in a fully un-escaped form (except for the QueryString)
suitable only for display. This format should not be used in HTTP
headers or other HTTP operations.

GetEncodedUrl()

Returns the combined components of the
request URL in a fully escaped form suitable for use in HTTP headers
and other HTTP operations.

Usage:

using Microsoft.AspNetCore.Http.Extensions;
...
string url = HttpContext.Request.GetDisplayUrl();
// or
string url = HttpContext.Request.GetEncodedUrl();

Getting absolute URLs using ASP.NET Core

For ASP.NET Core 1.0 Onwards

/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static class UrlHelperExtensions
{
/// <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 IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}

/// <summary>
/// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
/// virtual (relative) path to an application absolute path.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="contentPath">The content path.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteContent(
this IUrlHelper url,
string contentPath)
{
HttpRequest request = url.ActionContext.HttpContext.Request;
return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
}

/// <summary>
/// Generates a fully qualified URL to the specified route by using the route name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteRouteUrl(
this IUrlHelper url,
string routeName,
object routeValues = null)
{
return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
}

Bonus Tip

You can't directly register an IUrlHelper in the DI container. Resolving an instance of IUrlHelper requires you to use the IUrlHelperFactory and IActionContextAccessor. However, you can do the following as a shortcut:

services
.AddSingleton<IActionContextAccessor, ActionContextAccessor>()
.AddScoped<IUrlHelper>(x => x
.GetRequiredService<IUrlHelperFactory>()
.GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

ASP.NET Core Backlog

UPDATE: This won't make ASP.NET Core 5

There are indications that you will be able to use LinkGenerator to create absolute URLs without the need to provide a HttpContext (This was the biggest downside of LinkGenerator and why IUrlHelper although more complex to setup using the solution below was easier to use) See "Make it easy to configure a host/scheme for absolute URLs with LinkGenerator".

Getting full url of any file in ASP.Net MVC

You can use the following code to replace "~/" to absoulute URL.

System.Web.VirtualPathUtility.ToAbsolute("~/")

Edit:

First you need to define a method.

public static string ResolveServerUrl(string serverUrl, bool forceHttps)
{
if (serverUrl.IndexOf("://") > -1)
return serverUrl;

string newUrl = serverUrl;
Uri originalUri = System.Web.HttpContext.Current.Request.Url;
newUrl = (forceHttps ? "https" : originalUri.Scheme) +
"://" + originalUri.Authority + newUrl;
return newUrl;
}

Now call this method will return the complete absolure url.

ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/images/image1.gif"),false))

The output will be http://www.yourdomainname.com/images/image1.gif

How to generate a URL for ASP.NET MVC action, including hostname and port?

Sample Image

Url.Action("Action", "Controller", null, Request.Url.Scheme);

How to include the following in the Form Action attribute?

1. Protocol(http:// or https://)
2. HostName

3. QueryString

4. Port

@{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
@using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { @action = actionURL }))
{
}

How to get current page URL in MVC 3

You could use the Request.RawUrl, Request.Url.OriginalString, Request.Url.ToString() or Request.Url.AbsoluteUri.



Related Topics



Leave a reply



Submit