Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

html encode - "<" in a text box in ASP.NET --> how to allow it?

I have a textfield which displays a string which contains < and >. The code throws an error because of that. How can I allow the usage of those chars in my textfield?

Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem is that when this gets posted to server, it will not work, doesn't matter what you try. This is the ASP.NET XSS protection, which can be disabled like so:

<%@ Page ... ValidateRequest="false" %>

Trouble is, you'll have to be very careful validating all the postback yourself. Easier way is to escape all the contents of textbox using javascript just before posting. You can escape it using same HTML escaping, then unescape in server side code.

Update: Example of escaping. This will flash the changed text on screen before postback - ideal solution is to use a hidden field for this, i.e. assign value to a hidden field, instead of that same field. This is the simplest version:

<script>
  function EscapeField(){
    document.getElementById("your client control ID").value = 
       escape(document.getElementById("your client control ID").value);
  }
</script>

And in code-behind:

this.ClientScript.RegisterOnSubmitStatement(this.GetType(), 
    "EscapeField", "EscapeField();")

Update: Again, warning - if you save HTML in your database like this, and then just display it to the client, you are directly vulnerable to XSS attacks. There are worms out there that will find and exploit your web site. Make sure you cleanse the HTML you are getting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...