Getting absolute URLs using ASP.NET Core

asp.net core get base url
asp.net core 2 get current url
asp.net core urlhelper example
asp.net core 2.0 get request url
asp.net mvc get base url in javascript
asp.net core get current domain
asp net core get hostname
asp net core get request in view

In MVC 5, I had the following extension methods to generate absolute URLs, instead of relative ones:

public static class UrlHelperExtensions
{
    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);
    }

    public static string AbsoluteContent(
        this UrlHelper url,
        string contentPath)
    {
        return new Uri(url.RequestContext.HttpContext.Request.Url, url.Content(contentPath)).ToString();
    }

    public static string AbsoluteRouteUrl(
        this UrlHelper url,
        string routeName,
        object routeValues = null)
    {
        string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
        return url.RouteUrl(routeName, routeValues, scheme);
    }
}

What would the equivalent be in ASP.NET Core?

  • UrlHelper.RequestContext no longer exists.
  • You can't get hold of the HttpContext as there is no longer a static HttpContext.Current property.

As far as I can see, you would now require the HttpContext or HttpRequest objects to be passed in also. Am I right? Is there some way to get hold of the current request?

Am I even on the right track, should the domain now be an environment variable, which is simple appended to the relative URL? Would this be a better approach?

How to Get the Base URL in ASP.NET, Learn how to get the base URL in ASP.NET. It doesn't have to be as NET Core and dependency injection. <returns>The absolute URL. Noting the Route name of the target action, get the relative URL using the controller's URL property as follows: var routeUrl = Url.RouteUrl("*Route Name Here*", new { *Route parameters here* }); Create an absolute URL var absUrl = string.Format("{0}://{1}{2}", Request.Scheme, Request.Host, routeUrl); Create a new Uri

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 URL's 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 Absolute URL's using ASP.NET -iaspnetcore.com, NET Core to create web apps and services that are fast, secure, Getting Absolute URL's using ASP. In MVC 5, I had the following extension methods to generate absolute URL's, instead of relative ones public static string AbsoluteAction( There are multiple ways to set the URLs that ASP.NET Core binds to on startup. I have an old post about the various options available to you that applies to ASP.NET Core 1.0, but the options available in ASP.NET Core 3.x are much the same: UseUrls() - Set the URLs to use statically in Program.cs.

If you simply want a Uri for a method that has a route annotation, the following worked for me.

Steps
Get Relative URL

Noting the Route name of the target action, get the relative URL using the controller's URL property as follows:

var routeUrl = Url.RouteUrl("*Route Name Here*", new { *Route parameters here* });
Create an absolute URL
var absUrl = string.Format("{0}://{1}{2}", Request.Scheme,
            Request.Host, routeUrl);
Create a new Uri
var uri = new Uri(absUrl, UriKind.Absolute)
Example
[Produces("application/json")]
[Route("api/Children")]
public class ChildrenController : Controller
{
    private readonly ApplicationDbContext _context;

    public ChildrenController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: api/Children
    [HttpGet]
    public IEnumerable<Child> GetChild()
    {
        return _context.Child;
    }

    [HttpGet("uris")]
    public IEnumerable<Uri> GetChildUris()
    {
        return from c in _context.Child
               select
                   new Uri(
                       $"{Request.Scheme}://{Request.Host}{Url.RouteUrl("GetChildRoute", new { id = c.ChildId })}",
                       UriKind.Absolute);
    }


    // GET: api/Children/5
    [HttpGet("{id}", Name = "GetChildRoute")]
    public IActionResult GetChild([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return HttpBadRequest(ModelState);
        }

        Child child = _context.Child.Single(m => m.ChildId == id);

        if (child == null)
        {
            return HttpNotFound();
        }

        return Ok(child);
    }
}

Getting the base URL for an ASP.NET Core MVC web application in , The AbsoluteContent is an extension method that I added to my application to get the full URL and not only the path. public static class  It seems to be quicker to code this way. However, there are times that I need to generate absolute URL for public facing websites where SEO matters. Quickly google "why absolute url matters in seo", there is quite a number of blogs or articles promoting the use of absolute URLs.

You don't need to create an extension method for this

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

Generate absolute URLs in ASP.NET MVC, Generate absolute URLs in ASP.NET MVC. Sometimes it's easier to create relative URL in development using Url.Content("~/yourimage.png"). take a look at this answer, but I don't think an absolute url is required in your case. Here is a summary of what you will find in that answer: 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(); }

This is a variation of the anwser by Muhammad Rehan Saeed, with the class getting parasitically attached to the existing .net core MVC class of the same name, so that everything just works.

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// <see cref="IUrlHelper"/> extension methods.
    /// </summary>
    public static partial 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);
        }
    }
}

Make it easy to configure a host/scheme for absolute URLs with , Make it easy to configure a host/scheme for absolute URLs with Or a way to use IUrlHelper without all the setup code to get it working nicely. See: https://​github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/  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.

How to get an Absolute URLs in ASP.NET MVC without HttpContext , One can now get an absolute URL of actions in a different thread and don't need an HttpContext nor UrlHelper . I'm using this with FluentScheduler ( https://github. In ASP.NET Core the hosting model has completely changed from ASP.NET 4.x. Previously your application was inextricably bound to IIS and System.Web, but in ASP.NET Core, your application is essentially just a console app. You then create and configure your own lightweight HTTP server within your application itself.

How to Build Absolute Action URLs Using the UrlHelper Class , ASP.NET MVC ships with the UrlHelper class that makes route URL generation very easy. Read about how to generate absolute URLs instead  ASP.NET Core controllers use the Routing middleware to match the URLs of incoming requests and map them to actions.Routes templates: Are defined in startup code or attributes.

Creating Absolute Urls Of Controller Actions In ASP.NET MVC , An Example Of The Need To Use Absolute URLs Turns out you can call any of the UrlHelper methods and get an absolute URL directly if you call the ASP.​NET (4.x/MVC5 and Core), and other fullstack developer goodies. How to Get the Base URL in ASP.NET: Conclusion We’ve looked at a number of different ways to get the base URL in ASP.NET and .NET Core. There are a lot of options (almost too many), but I find the ones discussed here to be simple enough to get the job done.

Comments
  • Getting the absolute URL's what?
  • @im1dermike e.g. http://example.com/controller/action
  • We should now use IUrlHelper, rather than UrlHelper. All of the objects are a lot more disconnected in MVC 6. I think your option is the best one.
  • Doesn't work with RC1. View produces runtime error with extension method. Also, UriHelper link is dead.
  • @Mrchief I have updated the link (the namespaces have changed for RC2, so all those links to the dev branch are dead...). However I have just created an RC1 project, added @using Microsoft.AspNet.Http.Extensions to the Index.cshtml view and was able to use those extensions as in @Context.Request.GetDisplayUrl()
  • Would that do what I need as well? See stackoverflow.com/q/37928214/153923
  • This is ok but it seems an overkill to me, too much code for something simple. Could we just stick with string url = string.Concat(this.Request.Scheme, "://", this.Request.Host, this.Request.Path, this.Request.QueryString);
  • Referer isn't reliable, browsers aren't forced to send it. In other words, users can configure their browsers not to send referer, e.g. as a security measure.