0xDECAFBAD 0xDECAFBAD - 1 month ago 25
ASP.NET (C#) Question

ASP.NET MVC: Output validation

I am using the following method inside my ASP.NET MVC project to get some XML-data from another web service:

[HttpPost]
[ValidateInput(false)]
public ActionResult MyAction()
{
try
{
byte[] reqContent = Helper.GetBytes(Request.Unvalidated.Form["xml"]);

WebRequest request = WebRequest.Create("url");
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = reqContent.Length;
request.GetRequestStream().Write(reqContent, 0, reqContent.Length);

string responseXml = null;

using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseXml = reader.ReadToEnd();
}
}

return Content(responseXml, "text/xml");
}

catch(Exception)
{
return Json(new { Error = true });
}
}


The request inside the action works perfect and I get the right response when I debug the code. But unfortunately when I look at the Chrome Debug tools, the response code from my Action (not the request sent using
WebRequest
) is 500 with the error: "A potentially dangerous Request.Form value was detected from the client (xml=somexml).".

Is there some sort of output validation or do I miss something else here? Also the body of the POST-Request to the
MyAction
controller method consists of XML data, but using the
ValidateInput(false)
-attribute and the
Unvalidated
-property of the
Request
object, I get no exception and all works fine inside the method.

EDIT: SOLUTION

Thanks to the answer which I marked as accepted, I do not only changed the input validation on up to date standards, I also dug deeper into possible causes and realized that the problem was the global
OutputCacheAttribute
. This post finally solved the problem.

Answer

MVC is still validating the POST request before you hit your Action. The new way to go is to attribute the property that shall hold the XML with [AllowHtml]. [ValidateInput(false)] is deprecated. See Securing Your ASP.NET Applications.

public class PostXmlModel {
    [AllowHtml]
    public string Xml {get; set;}
}

[HttpPost]
public ActionResult MyAction(PostXmlModel postData) {
    string xml = postData.Xml;
    // ...
}

PS: to make [ValidateInput(false)] work, you would also need to set <httpRuntime requestValidationMode="2.0" /> in the web.config (not recommended). See Allow user to input html in asp net mvc validateinput or allowhtml.