添加不可解决的副本到ASP.NET MVC JsonResult

时间:2013-11-15 11:57:47

标签: javascript asp.net asp.net-mvc json security

根据这些帖子:

JSON unparseable cruft: Why so serious?

Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses?

Why does Google prepend while(1); to their JSON responses?

我想按照以下答案中提出的建议:How should web app developers defend against JSON hijacking?

是否有一种简单的方法可以为使用System.Web.Mvc.JsonResult构建的JSON响应添加一个不可解决的副本? security.se帖子建议我在回复开始时使用</*

1 个答案:

答案 0 :(得分:3)

您可以编写自定义操作结果来执行此操作:

public class SafeJsonResult: JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Write("</*");
        base.ExecuteResult(context);
    }
}

然后使用它而不是默认值:

public ActionResult Index()
{
    return new SafeJsonResult
    {
        Data = new { Foo = "bar" },
        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
    };
}