ASP.NET MVC Validation of Script Tags
I want to prevent a user from entering any <script>
tags inside a textarea box I have called story using very similar code to this:
if (ArticleToCreate.story.Contains("<script>") == true)
ModelState.AddModelError("Story", "No script tags allowed!");
Unfortuna开发者_如何学Pythontely this won't work because it's looking for <script>
exactly as it is rather than looking for <script>some code</script>
or some code`
Can anyone help? I want to use very similar code to as shown above and not any Service Layers or Model scripts. Thanks
By default, MVC won't allow this. If you explicitly allow it (e.g., with [ValidateInput(false)]
), then you need to use a tool like the Microsoft Web Protection Library to sanitize the input.
If you need to allow users to enter some HTML but not any HTML, I recommend investigating the Microsoft Web Protection Library, which includes methods for making user-entered HTML fragments "safe".
I agree with Matt Greer in saying that trying to create your own solution for recognizing illegal tags is a bad idea. There are so many attack vectors to inject script into HTML that you won't be able to guard against all of them. (See this XSS Cheat Sheet for a sampling, but it's out of date so there are probably more.)
you can use html encoding to obtain what you are looking for, something like this.
<%: model.story %> <---------that would help you, im assuming that you are using asp.net mvc 2 if not you can use something like this:
<%=Html.Encode(Model.story)%> <-----that's for asp.net mvc but that's for server side validation you can always add you own client side validation.
精彩评论