What to do for input sanitization?
I need to start worrying about user input. I notice the htmlhelper class do开发者_JAVA百科esnt do a great job of this. Can anyone suggest a nice framework for input sanitization? I'm using asp.net mvc2.
DataAnnotations are a good start for model validation. See this link for details on how to set up data annotations. They may be used in conjunction with the Microsoft MVC javascript libraries or jQuery to perform client side validation, and additionally may be used server-side to validate whether the model, once bound, is valid. See the ModelState.IsValid property.
While Annotations may help prevent and catch bad user input, they will not "sanitize" the input for you. If you are willing to accept bad input and want to handle its sanitization, a custom model binder would be a good place to start. Scott provides a good scenario of how to implement one here. . In a custom binder, you could pass text input thorough a series of string cleansing methods to strip out unwanted characters or standardize formatting, etc.
The combination of both of these approaches should equip you with the ability to handle almost any sanitization you may need.
The HtmlHelper class is for HTML output and not input, so I don't understand what do you mean by not doing a great job for user input sanitation. There are different ways of doing input validation like data annotations or using some third party framework like FluentValidation. If you are using a SQL database you should also make sure to avoid SQL injection by using prepared statements and parametrized queries. Also when you need to show user input on the page you should always make sure to properly HTML encode it using <%= Html.Encode("some user input") %>
or the newer syntax <%: "some user input" %>
.
I recommend you don't sanitize the input, rather, sanitize the output.
This avoids possible improper sanitation or corrupting the actual user input.
Let the user submit HTML, just make sure that when it's displayed, it's always encoded.
As Darin stated, use <%: %>
syntax or <%= Html.Encode() %>
to take care of this
精彩评论