Ashok Padmanabhan
Ashok Padmanabhan

Reputation: 2120

How to allow a user to enter html comments

Using MVC, EF 4.2. I am working on an application that has a comment section. Right now if a user enters a comment that contains HTML e.g.

<b>text</b>

and hits submit i get the message "A ptentially dangerous Request.Form value was detected..."

  1. How do i handle html on the way into the db? Should I just strip the html? Or encode it? I tried server.htmlencode the text but i still had the same error message.

I have read a number of posts on the matter including some here at SO - this one and this one

Ideally, i'd like to be able to allow a limited number of html tags such as em strong, a. Would Anti-XSS, HTML Agility, some kind of BB code, or a markdown style editor still be the recommended way? I know Jeff has a whitelist bit of code - however it is few yrs old.

Upvotes: 2

Views: 817

Answers (4)

Ashok Padmanabhan
Ashok Padmanabhan

Reputation: 2120

My solution for allow html incomments is as follows:

  1. AllowHtml on the CommentText property in my comment class
  2. Allow a narrow subset of tags. Use an Html Sanitizer class to scrub Html and inline script that is not allowed via a whitelist
  3. Then save the result to the db as i normally would
  4. At output time, use Html.Raw to show the Html in the comments

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37533

MVC has an attribute that allows you to specify a property should allow html without disabling validation completely. It's still dangerous, but it can be limited to a single property so the risk can be mitigated. Here is the MSDN article for the AllowHtmlAttribute. Proper usage of the attribute should be to decorate the appropriate property in your model:

public class MyModel
{
    public MyModel()
    {

    }

    // Some other stuff in here

    [AllowHtml]
    [HttpPost]
    public string MyHtmlString { get; set; }

}

Upvotes: 0

competent_tech
competent_tech

Reputation: 44931

You may also need to set the requestValidationMode in your web.config:

</system.web>
  <httpRuntime requestValidationMode="2.0" />
</system.web>

See this link for more details.

Upvotes: 0

Rafay
Rafay

Reputation: 31043

you can do

[ValidateInput(false)]
public ActionResult foo()
{
}

or you can decorate the model property with AllowHtml

   public class Foo
    {
        [AllowHtml]
        public string bar{ get; set; }
    }

Upvotes: 1

Related Questions