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

11,040

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

Share:
11,040
Martin Shishkov
Author by

Martin Shishkov

Updated on July 27, 2022

Comments

  • Martin Shishkov
    Martin Shishkov over 1 year

    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