Getting Absolute Urls Using ASP.NET Core

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

How to get absolute URL's Path in ASP.NET Core 2.0?

.Contains() method help me to implement logic with given action url

public class AuthorizationRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var url=context.HttpContext.Request.Path.ToString()
if(url.Contains("/api/values/get/1"))
{
//do something
}
}
}

How to access current absolute Uri from any ASP .Net Core class?

You want the IHttpContextAccessor "configured or injected" in your Startup so later on when you use the helper during the context of a request you can use it to access the current HttpContext object.

You cannot store the context on a static field as that context only makes sense while serving a specific request. Typically you will leave the accessor in a static field and use it every time your helper is called.

  • Even worse you are using static fields with initializers, which are executed the first time the class is used. That means they are executed right before you call the Configure method, so there will be no IHttpContextAccessor yet configured and you will get those null references.

This would be a simple thing of writing what you want:

public static class Context
{
private static IHttpContextAccessor HttpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
}

private static Uri GetAbsoluteUri()
{
var request = HttpContextAccessor.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
uriBuilder.Path = request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
return uriBuilder.Uri;
}

// Similar methods for Url/AbsolutePath which internally call GetAbsoluteUri
public static string GetAbsoluteUrl() { }
public static string GetAbsolutePath() { }
}

One more thing to bear in mind:

  • In the original question, the helper was created as a static class because they were created as extension methods. If you are not using extension methods you are not forced to use a static class.

How to get absolute path in ASP.Net Core alternative way for Server.MapPath

As of .Net Core v3.0, it should be IWebHostEnvironment to access the WebRootPath which has been moved to the web specific environment interface.

Inject IWebHostEnvironment as a dependency into the dependent class. The framework will populate it for you

public class HomeController : Controller {
private IWebHostEnvironment _hostEnvironment;

public HomeController(IWebHostEnvironment environment) {
_hostEnvironment = environment;
}

[HttpGet]
public IActionResult Get() {
string path = Path.Combine(_hostEnvironment.WebRootPath, "Sample.PNG");
return View();
}
}

You could go one step further and create your own path provider service abstraction and implementation.

public interface IPathProvider {
string MapPath(string path);
}

public class PathProvider : IPathProvider {
private IWebHostEnvironment _hostEnvironment;

public PathProvider(IWebHostEnvironment environment) {
_hostEnvironment = environment;
}

public string MapPath(string path) {
string filePath = Path.Combine(_hostEnvironment.WebRootPath, path);
return filePath;
}
}

And inject IPathProvider into dependent classes.

public class HomeController : Controller {
private IPathProvider pathProvider;

public HomeController(IPathProvider pathProvider) {
this.pathProvider = pathProvider;
}

[HttpGet]
public IActionResult Get() {
string path = pathProvider.MapPath("Sample.PNG");
return View();
}
}

Make sure to register the service with the DI container

services.AddSingleton<IPathProvider, PathProvider>();

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();


Related Topics



Leave a reply



Submit