How to allow HTML string in ASP.NET MVC

By FoxLearn 11/10/2024 1:40:45 AM   81
In ASP.NET MVC, HTML strings are considered dangerous because they can contain malicious code, such as JavaScript, that can lead to Cross-Site Scripting (XSS) attacks.

To allow HTML input, you can add [ValidateInput(false)] attribute in POST action. This allows HTML input in action level, that is, input will be not validated for all fields.

For example:

[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Create(Article article)
{
}

In ASP.NET MVC, you can allow HTML markup in a request during model binding by disabling request validation for a specific property using the [AllowHtml] attribute. This attribute bypasses the default request validation, which typically prevents potentially dangerous HTML or script content from being included in user input.

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    [AllowHtml]
    public string Content { get; set; }
}

Add either [ValidateInput(false)] attribute in a controller action level or add [AllowHtml] attribute to a specific property in data class. [AllowHtml] is preferred.

However, disabling request validation can expose your application to script exploits like Cross-Site Scripting (XSS) attacks. Therefore, it is strongly recommended that you explicitly validate and sanitize any input where request validation is disabled to ensure that malicious content is not processed or rendered in your application.