2

I am using Json to send update information to the following controller action:

    [HttpPost]
    public JsonResult JsonUpdate(string pk, string rk, string fld, string val) {
        Content content = null;
        try {
            if (fld == "TempRowKey") {
                content = contentService.Get(pk, rk);
                rk = utilityService.DotFormatToRowKey(val);
                contentService.UpdateRowKey(content, rk, User.Identity.Name);
            } else {

I realize it's an added protection in MVC that's causing the problem but I need to be able to pass HTML code in the val argument and I am getting the following error:

A potentially dangerous Request.Form value was detected from the client (val="...e HashMap <K,V>, LinkedHashMap..."). 

Note that the is valid text that an admin person entered. This screen is only used by admins and so I am okay with no protection for the field.

Looks like there were some changes between MVC2, 3 and 4.

What are the ways I can avoid this problem with MVC3 and MVC4. I saw there's another post like mine on stackoverflow but it does not really address the problem.

Note I am looking for something local that I can apply to just this action. I saw some suggestions on the web but it looks like there's confusion between how to handle this with the different MVC versions. Is the best way to encode and decode the data and if so how could I do that?

tereško
  • 58,060
  • 25
  • 98
  • 150
Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

3
[ValidateInput(false)]
public JsonResult JsonUpdate(string pk, string rk, string fld, string val)
{
    ...

However, you should be able to do something like this as well:

public class MyJsonUpdateModel
{
    public string pk { get; set; }
    public string rk { get; set; }
    public string fld { get; set; }

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

// [ValidateInput(false)] not needed because model states HTML is allowed
public JsonResult JsonUpdate(MyJsonUpdateModel model)
{
danludwig
  • 46,965
  • 25
  • 159
  • 237
  • Thanks for the suggestion. I like your second suggestion as I've never seen a viewmodel used with json. Do you think it would be better for me to do this or to encode the data before storage and then decode? – Alan2 Aug 04 '12 at 11:50
  • @Gemma it's up to you, but I would recommend against doing ValidateInput(false). Rather than encoding before request and decoding after request, it would probably be easier to just accept the potentially unsafe (possible HTML) input, and then just check/validate it in the controller before doing anything with it. – danludwig Aug 04 '12 at 12:07
0
public class MyModel{
  [AllowHtml]
  public string  Text{get;set;}
}

You need to add [AllowHtml] attribute to the field. Also make sure you dont add a FormCollection model to the Action, you can see https://stackoverflow.com/a/4866070/1431191

Community
  • 1
  • 1
Layinka
  • 405
  • 1
  • 4
  • 13