How can I get my webapp's base URL in ASP.NET

2019-01-02 14:41发布

How can I quickly determine what the root URL is for my ASP.NET MVC application? I.e., if IIS is set to serve my application at http://example.com/foo/bar, then I'd like to be able to get that URL in a reliable way that doesn't involve getting the current URL from the request and chopping it up in some fragile way that breaks if I re-route my action.

The reason that I need the base URL is that this web application calls another one that needs the root to the caller web application for callback purposes.

20条回答
泪湿衣
2楼-- · 2019-01-02 14:44

You could have a static method that looks at HttpContext.Current and decides which URL to use (development or live server) depending on the host ID. HttpContext might even offer some easier way to do it, but this is the first option I found and it works fine.

查看更多
旧时光的记忆
3楼-- · 2019-01-02 14:45

Maybe it is extension or modification of the answers posted here but I use simply the following line and it works:

Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~")

When my path is: http://host/iis_foldername/controller/action
then I receive : http://host/iis_foldername/

查看更多
浪荡孟婆
4楼-- · 2019-01-02 14:46

For ASP.NET MVC 4 it is a bit different:

string url = HttpContext.Request.Url.AbsoluteUri;
查看更多
几人难应
5楼-- · 2019-01-02 14:48

This is working in ASP .NET MVC 4 In any controller action you can write: 1stline gets the whole url+Query String. 2nd line remove local path & query ,last '/' symbol. 3rd line add '/' symbol at last position.

Uri url = System.Web.HttpContext.Current.Request.Url;
string UrlLink = url.OriginalString.Replace(url.PathAndQuery,"");
UrlLink = String.Concat(UrlLink,"/" );
查看更多
旧人旧事旧时光
6楼-- · 2019-01-02 14:48

For url with aplication alias like http://example.com/appAlias/... You can try this:

var req = HttpContext.Current.Request;
string baseUrl = string.Format("{0}://{1}/{2}", req.Url.Scheme, req.Url.Authority, req.ApplicationPath);
查看更多
春风洒进眼中
7楼-- · 2019-01-02 14:49

The following snippet works nicely for me in MVC4, and doesn't need an HttpContext available:

System.Web.HttpRuntime.AppDomainAppVirtualPath
查看更多
登录 后发表回答