【问题标题】:ASP.NET MVC: Output validationASP.NET MVC:输出验证
【发布时间】:2016-10-18 10:16:12
【问题描述】:

我在我的 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 调试工具时,我的操作(不是使用 WebRequest 发送的请求)的响应代码为 500,错误为:“从客户端检测到潜在危险的 Request.Form 值( xml=somexml)。"。

是否有某种输出验证或者我在这里错过了其他东西?此外,MyAction 控制器方法的 POST-Request 正文由 XML 数据组成,但使用 ValidateInput(false)-attribute 和 Request 对象的 Unvalidated-property,我没有例外,一切正常在方法内部。

编辑:解决方案

感谢我标记为已接受的答案,我不仅根据最新标准更改了输入验证,还深入挖掘了可能的原因并意识到问题出在全球 OutputCacheAttributeThis post终于解决了问题。

【问题讨论】:

    标签: c# asp.net xml asp.net-mvc


    【解决方案1】:

    在您点击 Action 之前,MVC 仍在验证 POST 请求。新的方法是使用[AllowHtml] 为应该保存XML 的属性赋予属性。 [ValidateInput(false)] 已弃用。 见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:要使[ValidateInput(false)] 工作,您还需要在web.config 中设置<httpRuntime requestValidationMode="2.0" />(不推荐)。见Allow user to input html in asp net mvc validateinput or allowhtml

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多