Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ASP.NET MVC application's base url in Startup.cs file?

I am looking for a way to get the root url of my web application so I wouldn't have to use a hardcoded string where I need it.

So far I've tried to get it this way:

var request = HttpContext.Current.Request;

var url = string.Format("{0}://{1}",
          request.Url.Scheme,
          request.Url.Authority);

but unfortunately this doesn't give me the desired result when executed from the Startup class, I got http://127.0.0.1

like image 316
Martin Shishkov Avatar asked Dec 17 '15 13:12

Martin Shishkov


People also ask

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.

How can I get baseUrl in ASP.NET Core?

httpContextAccessor = httpContextAccessor; } public void OnGet() { var baseUrl = httpContextAccessor. HttpContext?. Request. BaseUrl(); // ... } }


1 Answers

Given a full URL such as "http://example.com/MyApplication/Controller/Action", you can get some of this information from the System.Web.Hosting.HostingEnvironment.ApplicationHost object. You can get the following:

ApplicationVirtualPath -> "/MyApplication" SiteName => "Default Web Site" However, you will not be able to get the domain name before an actual request comes in. This is because an IIS website can accept requests for many different domains, some of which are only known via DNS and never configured anywhere.

For example, your website could respond to both mydomain.com and www.mydomain.com. Which is the correct one that you want to put in your link?

You can configure your IIS website to only accept connections that request a particular host, but that cannot be retrieved from an ASP.NET application.

Reference : Getting a web application's URI during startup

like image 170
Hugo Hilário Avatar answered Oct 27 '22 19:10

Hugo Hilário