Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Base URL in ASP.Net Core

I've just recently switched over from ASP.NET MVC to using .Core 2 and I can't figure out how to get the current URL in Core. I could get it easily enough using the Request in previous asp.net versions, but since that's no long valid in .Net Core I'm at a loss.

I haven't been able to find any way from my google searching as of now.

Any help is appreciated. Thanks!

like image 526
Memedon Avatar asked Oct 11 '18 21:10

Memedon


People also ask

How do I find the URL of a base URL?

There's nothing in the Android URI class that gives you the base URL directly- As gnuf suggests, you'd have to construct it as the protocol + getHost(). The string parsing way might be easier and let you avoid stuffing everything in a try/catch block.

How can I get baseUrl in ASP.NET Core?

var baseUrl = string. Format(“{0}://{1}{2}”, Request. Url. Scheme, Request.

How do I find the base URL of a controller?

How to Get the Base URL in an MVC Controller. Here's a simple one-liner to get the job done. var baseUrl = string. Format(“{0}://{1}{2}”, Request.


1 Answers

In the ConfigureServices method of your Startup.cs file, add the line:

services.AddHttpContextAccessor();

and you will now have access to the IHttpContextAccessor interface throughout your code when using dependency injection.

Usage as follows:

public class CustomerRepository
{
    private readonly IHttpContextAccessor _context;

    public CustomerRepository(IHttpContextAccessor context)
    {
        _context = context;
    }

    public string BaseUrl()
    {
        var request = _context.HttpContext.Request;
        // Now that you have the request you can select what you need from it.
        return string.Empty;
    }
}

Hope this answers your question :)

like image 61
Christopher Lake Avatar answered Oct 05 '22 10:10

Christopher Lake