2016-01-18

Disable Validation When Posting XML data (C#, ASP.NET MVC)

When you need to submit (post) XML back to ASP.NET MVC controller the page might get broken with message about dangerous content. ASP.NET MVC is protecting your site from injecting scripts or any other irregular content.

Request validation is a feature in ASP.NET that examines an HTTP request and determines whether it contains potentially dangerous content. In this context, potentially dangerous content is any HTML markup or JavaScript code in the body, header, query string, or cookies of the request. ASP.NET performs this check because markup or code in the URL query string, cookies, or posted form values might have been added for malicious purposes.

How to disable request validation in ASP.NET MVC?
To disable request validation in an ASP.NET MVC application, you must change request validation to occur earlier in the sequence of request processing. In the Web.config file, make the following setting:

<system .web="">
  <httpruntime requestvalidationmode="2.0">
</httpruntime></system>

You must make change the Web.config file. The first change is to set the requestValidationMode attribute of the httpRuntime element to "2.0". This setting makes request validation occur later in the sequence of request processing events. The setting is required for applications that use ASP.NET 4 and later, because as of ASP.NET 4, request validation takes place earlier in the request life cycle than it did in previous versions of ASP.NET.

To disable request validation for an action method, mark the method with the attribute ValidateInput(false), as shown in the following example:o disable request validation for an action method, mark the method with the attribute ValidateInput(false), as shown in the following example:
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(string comment) 
{
    if (ModelState.IsValid) 
    {
        //  Etc.
    }
    return View(comment);
}

To disable request validation for a specific property, mark the property definition with the AllowHtml attribute:
[AllowHtml]
public string Prop1 { get;  set; }
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:
var rawComment = Request.Unvalidated().Form["comment"];


Reference: https://msdn.microsoft.com/en-us/library/hh882339.aspx

No comments:

Post a Comment