URL 根字符“~”在 ASP.NET MVC 中的行为不一致
URL Root character "~" does not behave consistently in ASP.NET MVC
我正在使用 ASP.NET 5. 在我的本地机器上我使用 http://localhost
但在我的服务器上我部署
至 http://server/MyApp
我的 _Layout.cshtml
中有以下行
<link href="~/lib/jquery-ui/base/core.css" rel="stylesheet" />
在没有“~”的情况下呈现为
<link href="/lib/jquery-ui/base/core.css" rel="stylesheet" />
然后在另一个地方我通过 HTML 助手生成输出
@Html.MyCustomHtmlButton(model=>model.Id)
string output="<a href=\""+ "~/area1/folder2/index" +"\">";
output += ".." + "</a>";
return new HtmlString(output.ToString());
但是这会使用“~”
呈现 html
<a href="~/area1/folder1/index" class="btn btn-sm btn-primary">
<i class="glyphicon glyphicon-remove-circle"></i>Cancel</a>
如果你点击它,你将被重定向到
http://localhost:59693/area1/controller11/edit/~/area1/controller1/index
因为在 html 中呈现“~”。
如何修复它,使“~”呈现到正确的根,以便 http://localhost
和 http://server/MyApp
都能正常工作?
您可以使用如下Ur.Action()
方法
string output="<a href=\""+Url.Action("index", "controller1", new {area="area1"})+"\">";
更新:
如果您在 class 库中使用它,那么只需使用
string output="<a href=\""+"/area1/controller1/index"+"\">";
像这样的波浪号只有在视图中用作纯文本时才有效。通过自己构建 HtmlString
,您将绕过该 URI 的 Razor,因此无法解析波浪号。
只需使用 @Url.Action()
构建 URI。
我正在使用 ASP.NET 5. 在我的本地机器上我使用 http://localhost
但在我的服务器上我部署
至 http://server/MyApp
我的 _Layout.cshtml
<link href="~/lib/jquery-ui/base/core.css" rel="stylesheet" />
在没有“~”的情况下呈现为
<link href="/lib/jquery-ui/base/core.css" rel="stylesheet" />
然后在另一个地方我通过 HTML 助手生成输出
@Html.MyCustomHtmlButton(model=>model.Id)
string output="<a href=\""+ "~/area1/folder2/index" +"\">";
output += ".." + "</a>";
return new HtmlString(output.ToString());
但是这会使用“~”
呈现 html<a href="~/area1/folder1/index" class="btn btn-sm btn-primary">
<i class="glyphicon glyphicon-remove-circle"></i>Cancel</a>
如果你点击它,你将被重定向到
http://localhost:59693/area1/controller11/edit/~/area1/controller1/index
因为在 html 中呈现“~”。
如何修复它,使“~”呈现到正确的根,以便 http://localhost
和 http://server/MyApp
都能正常工作?
您可以使用如下Ur.Action()
方法
string output="<a href=\""+Url.Action("index", "controller1", new {area="area1"})+"\">";
更新:
如果您在 class 库中使用它,那么只需使用
string output="<a href=\""+"/area1/controller1/index"+"\">";
像这样的波浪号只有在视图中用作纯文本时才有效。通过自己构建 HtmlString
,您将绕过该 URI 的 Razor,因此无法解析波浪号。
只需使用 @Url.Action()
构建 URI。