开发者

Validating Input in ASP.NET MVC

Any suggestions for best practice on validating/cleaning user input in ASP.NET MVC. It seems ValidateInput will almost always need to be set to False since it cant be handled from within the MVC framework (the error is thrown even before the Action Method is fired).

So how should the input be validated for malicious input. Do we have to manually screen each input and check it for characters such as <, >, " etc How about if we only wish to allow some types of input such as tags but forbid 开发者_StackOverflow社区 and other inputs? This must be a pretty common requirement of a web app now, but I can't see much in ASP.NET MVC to automate this.


So how should the input be validated for malicious input. \

It depends on what your application is doing with this input. If you are storing it in a relational database for example, well, as long as you use parametrized queries and properly encode the user request, relational database don't care about storing for example alert('foo'); in a given column. When you might get into trouble is when you try to fetch the result stored in this database and show it on some view. It is at that moment that you must ensure that the result is properly HTML encoded.

So for example let's suppose that you have stored some hyper dangerous string in your data store and you want to display it on your view. If you were using the Razor view engine you would simply:

@Html.DisplayFor(x => x.SomeProperty)

which will take care of properly HTML encoding the value of SomeProperty so that you don;t have to worry about.

And if you were using the WebForms view engine:

<%= Html.DisplayFor(x => x.SomeProperty) %>

So, as you can see there are two critical moments where you should be careful with the user input:

  • always use parametrized queries if you are storing this user input into a relational database
  • always HTML encode the value you have stored when time comes to render it on some view
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜