简体   繁体   English

NET中的HtmlInputText控件中如何编码特殊字符?

[英]How to encode special characters in HtmlInputText Control in .Net?

I have an input control 我有一个输入控件

<input id="firstNameField" type="text" runat="server" />

And I give it a value server-side 我给它提供了服务器端的价值

firstNameField.Value = "Me!"

How do I encode the "!" 我该如何编码“!” character for output? 输出字符? I tried this: 我尝试了这个:

firstNameField.Value = "Me&#33;"

But .Net responds with this: 但是.Net对此回应:

<input name="firstNameField" type="text" id="firstNameField" value="Me&amp;#33;" />

Causing the user to see Me&#33; 导致用户看到Me&#33; in the text box. 在文本框中。 I understand that this is part of .Net's built-in XSS protection. 我了解这是.Net内置XSS保护的一部分。 How do I get .Net to encode for special characters other than ampersand? 我如何获得.Net来编码除&以外的特殊字符?

在分配后面代码中的值时,使用HttpUtility.HtmlEncode(“ text”)

I wound up extending the HttpEncoder class like so: 我像这样扩展了HttpEncoder类:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Util;
using System.Text;
using System.IO;

/// <summary>
/// Summary description for CustomHttpEncoder
/// </summary>
public class CustomHttpEncoder : HttpEncoder
{
    //
    // TODO: Add constructor logic here
    //
    public CustomHttpEncoder()
    {
    }

    protected override void HtmlEncode(string value, TextWriter output)
    {
        if (value != null) {
            MyHtmlEncode(value, output);
        }
    }

    protected override void HtmlAttributeEncode(string value, TextWriter output)
    {
        if (value != null) {
            MyHtmlEncode(value, output);
        }
    }

    private void MyHtmlEncode(string value, TextWriter output)
    {
        if (value != null) {
            string encodedValue = "";

            for (int i = 0; i <= value.Length - 1; i++) {
                byte[] asciiVal = Encoding.ASCII.GetBytes(value.Substring(i, 1));
                encodedValue += "&#" + asciiVal(0).ToString + ";";
            }

            output.Write(encodedValue);
        }
    }

}

And then referencing it in Web.config: 然后在Web.config中引用它:

<system.web>
    <httpRuntime encoderType="CustomHttpEncoder" />

After that, all I had to do was set the value like normal: 之后,我要做的就是像平常一样设置值:

firstNameField.Value = "Me!"

Which automatically encodes every character for maximum tin-foil hat security: 自动对每个字符进行编码,以最大程度地保护锡纸帽子的安全性:

<input name="firstNameField" type="text" id="firstNameField" value="&#77;&#101;&#33;" />

This suits my purposes well enough, but I could see it being a PITA in other situations. 这非常适合我的目的,但是我可以看到它在其他情况下是PITA。 In that case, MyHtmlEncode() would need to be modified to suit such situations. 在这种情况下,需要修改MyHtmlEncode()以适应这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM