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

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


当前回答

简单地在一行中获取BaseUrl

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

//output example: https://stackoverflow.com

其他回答

对于MVC 4:

String.Format("{0}://{1}{2}", Url.Request.RequestUri.Scheme, Url.Request.RequestUri.Authority, ControllerContext.Configuration.VirtualPathRoot);

你也可以用这个。对于剃刀页,最好使用它比其他。

https://ml-software.ch/posts/getting-the-base-url-for-an-asp-net-core-mvc-web-application-in-your-static-javascript-files

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <base href='@Url.AbsoluteContent("~/")'>
    <title>@ViewBag.Title - ASP.NET Core Web Application</title>
    <!-- ... -->
</head>
<body>

这对我来说很好(也有负载均衡器):

@{
    var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
    var baseurl = urlHelper.Content(“~”);
}

<script>
    var base_url = "@baseurl";
</script>

特别是当您使用非标准端口号时,使用Request.Url.Authority一开始看起来是一个很好的引导,但在LB环境中失败了。

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

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

所以这里列出的这些方法都不适合我,但通过使用其中的一些答案,我找到了一些有用的方法:

public string GetBaseUrl()
{
    var request = HttpContext.Current.Request;
    var appUrl = HttpRuntime.AppDomainAppVirtualPath;

    if (appUrl != "/") 
        appUrl = "/" + appUrl;

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

    return baseUrl;
}

更新ASP。NET Core / MVC 6:

ASP。NET Core使这个过程更加痛苦,特别是当您深入代码时。你有两个选项来获取HttpContext

1)从控制器传入:

var model = new MyClass(HttpContext);

然后在模型中:

private HttpContext currentContext;

public MyClass(HttpContext currentContext)
{
    this.currentContext = currentContext;
}

2)也许更干净的方法是将它注入到你的类中,首先在你的Startup中注册类型:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddTransient<MyClass, MyClass>();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

然后像这样为你注射:

private HttpContext currentContext;

public MyClass(IHttpContextAccessor httpContextAccessor)
{
    currentContext = httpContextAccessor.HttpContext;
}

在任何情况下,这是更新的。net Core GetBaseUrl():

public string GetBaseUrl()
{
    var request = currentContext.Request;

    var host = request.Host.ToUriComponent();

    var pathBase = request.PathBase.ToUriComponent();

    return $"{request.Scheme}://{host}{pathBase}";
}