繁体   English   中英

ASP.NET MVC:输出验证

[英]ASP.NET MVC: Output validation

我在ASP.NET MVC项目中使用以下方法从另一个Web服务获取一些XML数据:

[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 });
    }
}

动作中的请求工作完美,调试代码时得到正确的响应。 但是不幸的是,当我查看Chrome调试工具时,来自我的Action(不是使用WebRequest发送的请求)的响应代码为500,错误为:“ 从客户端检测到潜在危险的Request.Form值(xml = somexml)。 ”。

是否有某种输出验证,或者我在这里错过了其他事情吗? 同样, MyAction控制器方法的POST-Request主体由XML数据组成,但是使用Request对象的ValidateInput(false)属性和Unvalidated -property时,我没有异常,并且在该方法内部一切正常。

编辑:解决方案

感谢我标记为接受的答案,我不仅更改了最新标准的输入验证,而且还更深入地研究了可能的原因,并意识到问题是全局OutputCacheAttribute 这个帖子终于解决了问题。

在您点击“操作”之前,MVC仍在验证POST请求。 新的方法是使用[AllowHtml]应保留XML的属性。 不推荐使用[ValidateInput(false)] 请参阅保护ASP.NET应用程序的安全

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

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

PS:要使[ValidateInput(false)]工作,还需要在web.config中设置<httpRuntime requestValidationMode="2.0" /> (不推荐)。 请参阅允许用户在asp net mvc validateinput或allowhtml中输入html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM