在mvc网站中设置基本标记中的URL路径的不同方法

时间:2015-04-17 09:30:10

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

您好我只是在我的MVC网站上传递这样的网址:

<base href="http:4546//localhost/" />

它适用于本地,但如果我在ISS上托管它。这个网址会产生问题。

如果我要删除4546这样的网址:

http://localhost/Home/Contact

然后它的工作。

我通过删除代码中的端口号来尝试它,但仍然在url端口号中显示自己。

我如何删除端口号或者是什么方式让我可以在公共端口号码80上托管它?

请告诉我缺少的地方。

由于

4 个答案:

答案 0 :(得分:6)

您可以创建一个基本控制器并添加此方法

 protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
            base.OnActionExecuting(filterContext);
            var request = HttpContext.Request;
            var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, HttpRuntime.AppDomainAppVirtualPath == "/" ? "" : HttpRuntime.AppDomainAppVirtualPath);
            ViewBag.BasePath = baseUrl;
  }

此方法OnActionExecuting将始终在每个请求上调用,并在您的代码中使用此viewbag。

这将解决您在代码中的每个位置写入的问题。

答案 1 :(得分:1)

我遇到了类似的问题,在某些IIS配置中,"Rufus is my dog. Rufus is a good boy." 标记(AngularJS必需)提供了错误的地址。我解决此问题的方法是将$transformRules = @" @RuleTemplate = "LdapClaims" @RuleName = "2" c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query = ";mail,sAMAccountName,userPrincipalName;{0}", param = c.Value); "@ Add-AdfsWebApiApplication -Name "My Web API" -AllowedClientTypes 6 -ApplicationGroupIdentifier "MyApp" -IssueOAuthRefreshTokensTo 2 -TokenLifetime 7 -Identifier {https://apphost/myapp/api/} -IssuanceTransformRules $transformRules 替换为:

base

这基本上是Sulay解决方案的简化版本,但到目前为止对我来说是有效的。

答案 2 :(得分:0)

如果打开html5模式,我需要设置base代码来源于使用AngularJS,因为它需要base才能正确路由。

我最终得到了这个方法:

private const string Action = "action";
private const string Controller = "controller";

public static string CurrentActionWithoutRouteReuse(this UrlHelper urlHelper)
{
    var routeValues = urlHelper.RequestContext.RouteData.Values;
    var actionName = (string)routeValues[Action];
    var controllerName = (string)routeValues[Controller];

    var routeValuesWithoutParams = new RouteValueDictionary(routeValues);
    routeValuesWithoutParams.Remove(Action);
    routeValuesWithoutParams.Remove(Controller);
    routeValuesWithoutParams.Keys
        .ToList().ForEach(parameterName => routeValuesWithoutParams[parameterName] = null);

    var url = urlHelper.Action(actionName, controllerName, routeValuesWithoutParams);

    return url.EndsWith("/") ? url : url + "/";
}

注意,这里我明确地将其他参数设置为null。这是因为MVC使用的路由重用,但我现在不需要。

答案 3 :(得分:0)

为什么不将其添加到您的页面中?

<base href="~/">

使用您的URL路径编译时,它将被替换。我这样做是为了使Angular(2+)应用程序能够正常工作,并且运行正常。