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!
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.
var baseUrl = string. Format(“{0}://{1}{2}”, Request. Url. Scheme, Request.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With