对 URL 进行 Html 编码是否有效
我的观点有以下代码片段:
<div id="recommendFooter">
<% string urlRecommend = Url.Action("RecommendProduct", "Products", new { url = ViewContext.RequestContext.HttpContext.Request.Url.ToString() }); %>
<div>
<a href="<%= urlRecommend %>">This product is awesome!</a>
</div>
</div>
这应该像这样输出 Html:
<div id="recommendFooter">
<div>
<a href="http://www.mysite.com/Products/RecommendProduct?url=http://www.mysite.com/products/productbykey/20" >This product is awesome!</a>
</div>
</div>
我不确定是否可以 Html-Encode urlRecommend 甚至值 ViewContext.RequestContext.HttpContext.Request.Url.ToString()。
我启用了请求 - 验证,但对于这一部分,我们假设我没有启用它。我可以并且应该在这里进行 Html 编码吗?
编辑1
我想这就是古法的建议:
<div id="recommendFooter">
<% string urlRecommend = Url.Action("RecommendProduct", "Products", new { url = Server.UrlEncode( ViewContext.RequestContext.HttpContext.Request.Url.ToString() )});
string urlRecommendXssSave = Server.HtmlEncode(urlRecommend );
%>
<div>
<a href="<%= urlRecommendXssSave %>">This product is awesome!</a>
</div>
</div>
I have the following snippet in my view:
<div id="recommendFooter">
<% string urlRecommend = Url.Action("RecommendProduct", "Products", new { url = ViewContext.RequestContext.HttpContext.Request.Url.ToString() }); %>
<div>
<a href="<%= urlRecommend %>">This product is awesome!</a>
</div>
</div>
This should output Html like this:
<div id="recommendFooter">
<div>
<a href="http://www.mysite.com/Products/RecommendProduct?url=http://www.mysite.com/products/productbykey/20" >This product is awesome!</a>
</div>
</div>
I am not shure if I can Html-Encode urlRecommend or even the value ViewContext.RequestContext.HttpContext.Request.Url.ToString().
I have Request - Validation enabled , but for this part lets assume I dont have it enabled. Can and should I Html-Encode here?
EDIT 1
I suppose this is what Guffa suggests:
<div id="recommendFooter">
<% string urlRecommend = Url.Action("RecommendProduct", "Products", new { url = Server.UrlEncode( ViewContext.RequestContext.HttpContext.Request.Url.ToString() )});
string urlRecommendXssSave = Server.HtmlEncode(urlRecommend );
%>
<div>
<a href="<%= urlRecommendXssSave %>">This product is awesome!</a>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该值应该是 HTML 编码的,因为它位于 HTML 代码的属性中,但这在这里没有任何区别,因为没有需要转义的字符。
您需要做的是将 URL 中的查询字符串中的值进行 URL 编码。
链接的 HTML 代码应如下所示:(
注意:我在您问题的值中保留了重复的
http://
,您也应该修复它。)The value should be HTML encoded as it's in an attribute in the HTML code, but that doesn't make any difference here as there are no characters that need escaping.
What you need to do is to URL encode the value in the query string in the URL.
The HTML code for the link should end up like this:
(Note: I preserved the duplicate
http://
in the value from your question, you should probably fix that also.)