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

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


当前回答

这是一个asp.net属性到MVC的转换。这是一个很好的方法。

声明一个helper类:

namespace MyTestProject.Helpers
{
    using System.Web;

    public static class PathHelper
    {
        public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
        {
            string appPath = string.Empty;

            if (httpRequestBase != null)
            {
                //Formatting the fully qualified website url/name
                appPath = string.Format("{0}://{1}{2}{3}",
                            httpRequestBase.Url.Scheme,
                            httpRequestBase.Url.Host,
                            httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
                            httpRequestBase.ApplicationPath);
            }

            if (!appPath.EndsWith("/"))
            {
                appPath += "/";
            }

            return appPath;
        }
    }
}

用法:

从控制器使用:

PathHelper.FullyQualifiedApplicationPath(ControllerContext.RequestContext.HttpContext.Request)

在视图中使用:

@using MyTestProject.Helpers

PathHelper.FullyQualifiedApplicationPath(Request)

其他回答

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

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

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

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

依赖IIS的诀窍在于,IIS绑定可能不同于您的公共url(我指的是WCF),特别是对于多主场的生产机器。我倾向于使用配置显式地为外部目的定义“基本”url,因为这往往比从Request对象中提取它更成功。

对于MVC 4:

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

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

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

使用

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

在MVC _Layout.cshtml中:

<base href="@Request.GetBaseUrl()" />

我们就是这么用的!

public static class ExtensionMethods
{
public static string GetBaseUrl(this HttpRequestBase request)
        {
          if (request.Url == (Uri) null)
            return string.Empty;
          else
            return request.Url.Scheme + "://" + request.Url.Authority + VirtualPathUtility.ToAbsolute("~/");
        }
}