【发布时间】:2018-06-30 15:26:34
【问题描述】:
我有下面一行想要编码的 aspx 链接:
Response.Redirect("countriesAttractions.aspx?=");
我试过以下方法:
Response.Redirect(Encoder.UrlPathEncode("countriesAttractions.aspx?="));
这是我尝试过的另一种方法:
var encoded = Uri.EscapeUriString("countriesAttractions.aspx?=");
Response.Redirect(encoded);
两者都重定向到没有编码 URL 的页面:
http://localhost:52595/countriesAttractions?=
我尝试了第三种方法:
Response.Redirect(Server.UrlEncode("countriesAttractions.aspx?="));
这次 url 本身被编码:
http://localhost:52595/countriesAttractions.aspx%3F%3D
但是,我从 UI 中收到一条错误消息:
HTTP Error 404.0 Not Found
The resource you are looking for has been removed, had its name changed, or
is temporarily unavailable.
Most likely causes:
-The directory or file specified does not exist on the Web server.
-The URL contains a typographical error.
-A custom filter or module, such as URLScan, restricts access to the file.
另外,我想编码另一种涉及解析会话字符串的 URL:
Response.Redirect("specificServices.aspx?service=" +
Session["service"].ToString().Trim() + "&price=" +
Session["price"].ToString().Trim()));
我尝试将编码方法包含在上面的代码中的方法:
Response.Redirect(Server.UrlEncode("specificServices.aspx?service=" +
Session["service"].ToString().Trim() + "&price=" +
Session["price"].ToString().Trim()));
我使用的上述编码方法显示的结果与我以前的服务器 URL 编码方法收到的结果相同。我不确定如何以正确的方式对 url 进行编码而不会出错。
以及使用 CommandArgument 对 URL 进行编码:
Response.Redirect("specificAttractions.aspx?attraction=" +
e.CommandArgument);
我尝试了以下编码:
Response.Redirect("specificAttractions.aspx?attraction=" +
HttpUtility.HtmlEncode(Convert.ToString(e.CommandArgument)));
但它没有工作。
有什么方法可以在不收到此类错误的情况下对 url 进行编码? 我希望输出类似于我的第二个结果,但我想查看页面本身而不是错误页面。
我尝试了在 stackoverflow 上找到的其他方法,例如自编码方法,但这些方法也不起作用。 在这种情况下,我将 AntiXSS 类库用于我尝试的方法,所以如果我可以使用 AntiXSS 库获得解决方案,那就太好了。 我需要将 URL 编码为我学校项目的一部分,所以如果我能得到解决方案,那就太好了。谢谢你。
【问题讨论】:
-
你的问题没有多大意义。我们不对 URL 进行编码,我们只对 URL 的参数进行编码。因此,我们对完整 URL 进行编码的唯一时间是当它作为另一个 URL 的参数传递时。或许您应该解释一下您要做什么,以便我们帮助您找到最好的方法。
-
好吧对不起,我不知道 URL 不能被编码,我从我的讲义中读到它可以被编码。我想要实现的是对通过 URL 传递的参数进行编码。例如带有会话解析和命令参数的 url,有什么方法可以在我的 URL 中对它们进行编码? @RacilHilan
-
是的。 HttpUtility.UrlEncode 方法。它接受一个字符串并返回编码版本。因此,您可以为每个参数调用一次。 msdn.microsoft.com/en-us/library/…
-
你能写一个我如何使用它的例子吗?也许可以使用我在问题中提供的网址之一来说明我如何以正确的方式做到这一点。您提供的链接非常模糊,没有提供任何示例。我以前使用过该方法,但它没有对我的网址进行编码。 @ADyson
-
我尝试了您建议的方法,我得到了相同的错误页面。 @ADyson