I would like to allow my users to submit a subset of xhtml that will be displayed to other users (likely I'll build a schema for it) but I want the server to handle validation more gracefully then hard rejecting invalid submissions. Instead I'd like the server to Html Encode invalid/harmful parts of the submissions (sanitize javascript and css etc.).
Is there any library (maybe asp.net mvc 2 has such functionali开发者_JS百科ty?) or do I have to develop my own?
Or maybe there is a javascript library that html encodes invalid parts and I can just have the server only accept that subset?
You could probably use Anti-XSS. See this SO question for relevant tips.
You could decorate the action you are posting to with the [ValidateInput]
attribute in order to accept dangerous characters:
[ValidateRequest(false)]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
And when the moment comes to show them on a page make sure you HTML encode them:
<%= Html.Encode(Model.SomeProperty) %>
or using the new syntax in ASP.NET 4:
<%: Model.SomeProperty %>
Also if you are using ASP.NET 4 make sure you put the following in your web.config:
<httpRuntime requestValidationMode="2.0" />
or the ValidateRequest
attribute might not be taken into account.
精彩评论