Should we sanitize non-string parameters passed to an action method?
For string parameters, we have to sanitize them in the action method as follows:
public ActionResult Br开发者_运维问答owse(string genre)
{
string message = HttpUtility.HtmlEncode(genre);
return View(message);
}
Is it necessary to sanitize non-string params as follows?
public ActionResult Details(int id)
{
int data = int.Parse(HttpUtility.HtmlEncode(id));
return View(data);
}
Personally, I recommend sanitizing these inputs in the view. If you're using the WebForms view engine, you can use <%: ... %>
to do this, or if you're using Razor you can use the @ operator. This also makes the flow of the data through the system view-independent, so your data and models can be shared more readily.
For example, HTML-encoding data before storing it in the database makes it very difficult to create at some future date a view which outputs the data as a CSV file. If the view is responsible for doing this, then the view can choose CSV-encoding or HTML-encoding as appropriate for its own application.
For string parameters, we have to sanitize them in the action method as follows:
public ActionResult Browse(string genre) {
string message = HttpUtility.HtmlEncode(genre); return View(message);
}
You shouldn't be doing anything like this in a controller action. If you intend to store this string into a database, go ahead and store it as is. A database doesn't care much about unencoded HTML. Of course when the time comes to output this to your view you will need to ensure that it is properly encoded:
<%= Html.Encode(message) %> // WebForms ASP.NET 2.0
<%: message %> // WebForms ASP.NET 4.0
@message // Razor ASP.NET 4.0
If you're using MVC, there is no reason to send the data to the view with HtmlEncode
for really any reason. The reason for this is because you can do it much easier in the view it's self.
<!-- WEB FORMS VIEW ENGINE -->
<!-- This is already encoded -->
<%: Model.genre %>
<!-- This is NOT encoded -->
<%= Model.genre %>
<!-- RAZOR VIEW ENGINE -->
<!-- This is already encoded -->
@Model.genre
<!-- This is NOT encoded -->
@MvcHtmlString.Create(Model.genre)
As for sanitizing, that's a different ball of wax all together. Jeff Atwood has some code here and talks about it here. Remember, you can store whatever user input in the database, it's the output that needs sanitizing AND html encoding.
As for encoding non-string parameters. It's usually not necessary, however the difference between <%: Model.genre %>
and <%= Model.genre %>
is pretty insignificant in your development time.
精彩评论