使用Attributes.Add时,.Net 4.0编码单引号

时间:2013-08-06 09:07:22

标签: c# asp.net encoding .net-4.0 asp.net-4.0

当我使用Attributes.Add将客户端事件添加到我的asp.net对象时,.Net 4.0编码单引号。在以前的版本中,这没有发生。

例如:

<asp:Image runat="server" ID="imgTest" ImageUrl="~/DateControl/cal.gif" />

 imgTest.Attributes.Add("onmouseover", "alert('Hello')");

当我查看客户端输出时,我正在

 <img id="ctl00_MainContent_calFromTimeStamp1_imgTest" onmouseover="alert(&#39;Hello&#39;)" src="../DateControl/cal.gif" style="border-width:0px;" />

我通过创建自定义编码器找到了一种解决方法:creating custom encoding routines但我不想因为这个问题而停止整个网站的编码。任何人都有解决方法或想法如何解决这个问题?

6 个答案:

答案 0 :(得分:4)

根据Microsoft的说法,您不应该使用WebControl.Attributes.Add()将JavaScript添加到HTML属性,因为它会对属性值进行编码:

  

您无法使用。将客户端脚本添加到WebControl实例   属性集合。要添加客户端脚本,请使用ClientScript   页面控件上的属性。

Source

建议是使用Page.ClientScript.RegisterExpandoAttribute(string controlId, string attributeName, string attributeValue, bool encode) method。在你的情况下,它看起来像这样:

Page.ClientScript.RegisterExpandoAttribute(
  imgTest.ClientID, 
  "onmouseover", 
  "alert('Hello')", 
  false /* Do not encode */
);

这将导致页面中的一段JavaScript设置客户端属性。

答案 1 :(得分:1)

在.NET中设置事件属性的最佳方法是调用单个函数:

imgTest.Attributes("message") = "Hello";
imgTest.Attributes("onmouseover") = "showMessage(this);"

在您的页面或注册脚本上:

function showMessage(ctrl) 
{
  alert(ctrl.getAttribute('message'));
}

答案 2 :(得分:0)

imgTest.Attributes.Add("onmouseover", "alert(\'Hello\')");

答案 3 :(得分:0)

感谢Franzo的link,其中复制并粘贴了以下答案:

  

您可以通过创建如下所示的类来关闭属性编码:

public class HtmlAttributeEncodingNot : System.Web.Util.HttpEncoder
{
    protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
    {
        output.Write(value);
    }
}
  

并将其添加到web.config下:

<httpRuntime encoderType="HtmlAttributeEncodingNot"/>
  

这给了我需要的控制权。

     

然而,现在我们必须担心新的控制可能取决于新的控制   标准4.0行为,不编码单引号,所以它仍然   不完美,不,不完美:安全更糟,因为   我们不知道发生了什么,所以这不是一个很好的解决方法   真。

     

我认为只有微软才能正确解决这个问题。其他人建议   这里需要一个HtmlAttributeString类:link如果有的话   是这样一个类,Attributes.Add可以采取这样的对象   对于它的值参数,那么我们将拥有我们需要的控件   试。

答案 4 :(得分:0)

不建议关闭属性编码。如果您尝试在默认情况下阻止编码,将来您的代码会出现许多奇怪的行为,您必须为不良做法付出代价。

.NET总是编码任何属性以阻止注入恶意脚本。所以你应该采用这种默认做法来保护你的程序。

答案 5 :(得分:-3)

您可以在任何引号字符前使用转义字符:

来源:

this.Attributes.Add("onmouseover", string.Format("$(this).attr(\'src\',\'{0}\')",this.Page.ClientScript.GetWebResourceUrl(typeof(SwapImage), urlenabledkey)));

渲染:

onmouseover="$(this).attr('src','/WebResource.axd?d=kHY3FE9nMsUOvDU-pPthg4KQvVrnXlcASyA7dFf6L