如何快速确定我的ASP的根URL是什么?NET MVC应用程序?例如,如果IIS设置为在http://example.com/foo/bar上为我的应用程序服务,那么我希望能够以一种可靠的方式获得该URL,而不涉及从请求中获取当前URL,并以某种脆弱的方式将其分割,如果我重新路由我的操作,这种方式就会中断。

我需要基本URL的原因是这个web应用程序调用另一个需要根的调用者web应用程序的回调目的。


当前回答

ASP。NET MVC 4有点不同:

string url = HttpContext.Request.Url.AbsoluteUri;

其他回答

我把它放在我的_Layout.cshtml的头部

 <base href="~/" />

简单地在一行中获取BaseUrl

string baseUrl = new Uri(Request.Url, Url.Content("~")).AbsoluteUri;

//output example: https://stackoverflow.com
@{
    var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
@baseurl

——输出 http://localhost:49626/TEST/

这是我的解决方案(使用。net core 3.1,在api控制器中):

string baseUrl = $"{Request.Scheme}://{Request.Headers.Where(h => h.Key == "Host").First().Value}";

也许这是一个更好的解决方案。

@{
   var baseUrl = @Request.Host("/");
}

使用

<a href="@baseUrl" class="link">Base URL</a>