ValidateInput(false) 与 AllowHtml [英] ValidateInput(false) vs AllowHtml

查看:25
本文介绍了ValidateInput(false) 与 AllowHtml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于创建备忘录的表单,为此我使用富文本编辑器来提供一些样式,这会创建 html 标签以应用样式.当我发布该文本时,mvc 会抛出一个错误以防止潜在的危险脚本,因此我必须特别允许它.

我找到了两种方法,一种是用 [ValidateInput(false)] 装饰控制器方法,另一种是用 ViewModel 属性装饰[AllowHtml].对我来说,[AllowHtml] 看起来更好,但我只发现该方法使用了 1 次,[ValidateInput(false)] 似乎是首选方法.

我应该使用哪种方法,两者有什么区别?

解决方案

ValidateInput 和 AllowHTML 与 通过一个例子一步一步地展示了这两个属性的重要性.

I have a form that is used to create a memo, to do that I am using a rich text editor to provide some styling, this creates html tags in order to apply style. When I post that text, the mvc throws an error to prevent potentially dangerous scripts, so I have to specifically allow it.

I have found 2 ways of doing this, one is to decorate the controller method with [ValidateInput(false)] and the other is to decorate the ViewModel attribute with [AllowHtml]. To me, [AllowHtml] looks much nicer, but I have only found that approach used 1 time and the [ValidateInput(false)] seems to be the preferred way.

Which method should I use and what are the differences between the two?

解决方案

ValidateInput and AllowHTML are directly connected with XSS security issues.

So let us first try to understand XSS.

XSS (cross-site scripting) is a security attack where the attacker injects malicious code while doing data entry. Now the good news is that XSS is by default prevented in MVC. So if any one tries to post JavaScript or HTML code he lands with the below error.

But in real time there are scenarios where HTML has to be allowed, like HTML editors. So for those kind of scenarios you can decorate your action with the below attribute.

[ValidateInput(false)]
public ActionResult PostProduct(Product obj)
{
    return View(obj);
}

But wait, there is a problem here. The problem is we have allowed HTML on the complete action which can be dangerous. So if we can have more granular control on the field or property level that would really create a neat, tidy and professional solution.

That’s where AllowHTML is useful. You can see in the below code I have decorated "AllowHTML" on the product class property level.

public class Product
{
    public string ProductName { get; set; }
    [AllowHtml]
    public string ProductDescription { get; set; }
}

So summarizing "ValidateInput" allows scripts and HTML to be posted on action level while "AllowHTML" is on a more granular level.

I would recommend to use "AllowHTML" more until you are very sure that the whole action needs to be naked.

I would recommend you to read the blog post Preventing XSS Attacks in ASP.NET MVC using ValidateInput and AllowHTML which demonstrates step by step about the importance of these two attributes with an example.

这篇关于ValidateInput(false) 与 AllowHtml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆