简体   繁体   中英

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

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

This worked for me:

var request = HttpContext.Current.Request;    
var url = request.Url.Scheme + "://" + request.Url.Authority + request.ApplicationPath.TrimEnd('/');

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM