Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

asp.net MvcValidationValidate Request

asp.net Mvc Problem Overview


How can I allow a user to input HTML into a particular field using ASP.net MVC.

I have a long form with many fields that get mapped to this complex object in the controller.

I would like to make one field (the description) allow HTML which I will preform my own sanitation on at a later point.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Add the following attribute the action (post) in the controller that you want to allow HTML for:

[ValidateInput(false)] 

Edit: As per Charlino comments:

In your web.config set the validation mode used. See MSDN:

<httpRuntime requestValidationMode="2.0" />

Edit Sept 2014: As per sprinter252 comments:

You should now use the [AllowHtml] attribute. See below from MSDN:

> For ASP.NET MVC 3 applications, when you need to post HTML back to > your model, don’t use ValidateInput(false) to turn off Request > Validation. Simply add [AllowHtml] to your model property, like so: > > public class BlogEntry { > public int UserId {get;set;} > [AllowHtml] > public string BlogText {get;set;} > }

Solution 2 - asp.net Mvc

What about [AllowHtml] attribute above property?

Solution 3 - asp.net Mvc

Add to model:

using System.Web.Mvc;

And to your property

        [AllowHtml]
        [Display(Name = "Body")]
        public String Body { get; set; }

This code from my point the best way avoid this error. If you are using HTML editor you will not have security issues because it already restricted.

Solution 4 - asp.net Mvc

Adding [AllowHtml] on the specific property is the recommended solution as there are plenty of blogs and comments suggesting to decrease the security level, which should be unacceptable.

By adding that, the MVC framework will allow the Controller to be hit and the code in that controller to be executed.

However, it depends on your code, filters, etc. how the response is generated and whether there is any further validation that might trigger another similar error.

In any case, adding [AllowHtml] attribute is the right answer, as it allows html to be deserialized in the controller. Example in your viewmodel:

[AllowHtml]
public string MessageWithHtml {get; set;}

Solution 5 - asp.net Mvc

I faced the same issue although i added [System.Web.Mvc.AllowHtml] to the concerning property as described in some answers.

In my case, i have an UnhandledExceptionFilter class that accesses the Request object before MVC validation takes place (and therefore AllowHtml has not effect) and this access raises a [HttpRequestValidationException] A potentially dangerous Request.Form value was detected from the client.

This means, accessing certain properties of a Request object implicitly fires validation (in my case its the Params property).

A solution to prevent validation is documented on MSDN

> To disable request validation for a specific field in a request (for example, for an input element or query string value), call the Request.Unvalidated method when you get the item, as shown in the following example

Therefore, if you have code like this

var lParams = aRequestContext.HttpContext.Request.Params;
if (lParams.Count > 0)
{
  ...

change it to

var lUnvalidatedRequest = aRequestContext.HttpContext.Request.Unvalidated;

var lForm = lUnvalidatedRequest.Form;
if (lForm.Count > 0)
{
  ...

or just use the Form property which does not seem to fire validation

var lForm = aRequestContext.HttpContext.Request.Form;
if (lForm.Count > 0)
{
  ...

Solution 6 - asp.net Mvc

If you need to allow html input for action-method parameter (opposed to "model property") there's no built-in way to do that but you can easily achieve this using a custom model binder:

public ActionResult AddBlogPost(int userId,
    [ModelBinder(typeof(AllowHtmlBinder))] string htmlBody)
{
    //...
}

The AllowHtmlBinder code:

public class AllowHtmlBinder : IModelBinder
{
	public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
	{
		var request = controllerContext.HttpContext.Request;
		var name = bindingContext.ModelName;
		return request.Unvalidated[name]; //magic happens here
	}
}

Find the complete source code and the explanation in my blog post: https://www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-particular-action-parameters/

Solution 7 - asp.net Mvc

URL Encoding the data works as well for me

For example

var data = '<b>Hello</b>'

In Browser call encodeURIComponent(data) before posting

On Server call HttpUtility.UrlDecode(received_data) to decode

That way you can control exactly which fields area allowed to have html

Solution 8 - asp.net Mvc

I have faced this problem during development of a E-Commerce site using NopCommerce, I got this solution by 3 different ways as like the previous answers. But according to the NopCommerce structure I didn't found those three at a time. I have just seen that there they are using just [AllowHtml] and it's working fine except any problem. As previously asked question

Personally I don't prefer [ValidateInput(false)] because i's skipping total model entity checking, which is insecure. But if anyone just write have a look here

[AllowHtml] 
public string BlogText {get;set;}

then it just skip only single property, and just allow only particular property and check hardly all other entities. Therefore it seems preferable towards mine.

Solution 9 - asp.net Mvc

In my case, the AllowHtml attribute was not working when combined with the OutputCache action filter. This answer solved the problem for me. Hope this helps someone.

Solution 10 - asp.net Mvc

You Can Use [AllowHtml] To Your Project For Example

 [AllowHtml]
 public string Description { get; set; }

For Use This Code To Class Library You Instal This Package

Install-Package Microsoft.AspNet.Mvc

After Use This using

using System.Web.Mvc;

Solution 11 - asp.net Mvc

None of the answers here worked for me unfortunately.

I ended up using Custom Model Binding and used a third-party Sanitizer.

See my self-answered question here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRabbiView Question on Stackoverflow
Solution 1 - asp.net MvcKelseyView Answer on Stackoverflow
Solution 2 - asp.net MvccryssView Answer on Stackoverflow
Solution 3 - asp.net MvcEugene BosikovView Answer on Stackoverflow
Solution 4 - asp.net MvcdiegosaswView Answer on Stackoverflow
Solution 5 - asp.net MvcViRuSTriNiTyView Answer on Stackoverflow
Solution 6 - asp.net MvcAlex from JitbitView Answer on Stackoverflow
Solution 7 - asp.net MvcsmjhuntView Answer on Stackoverflow
Solution 8 - asp.net MvcgdmanandamohonView Answer on Stackoverflow
Solution 9 - asp.net Mvcjd4w9View Answer on Stackoverflow
Solution 10 - asp.net MvcDiako HasaniView Answer on Stackoverflow
Solution 11 - asp.net Mvcom-haView Answer on Stackoverflow