JsonRequestBehavior equivalent in Json.Net with Asp.Net Mvc

本文关键字:Net with Mvc Asp Json equivalent in JsonRequestBehavior | 更新日期: 2023-09-27 18:27:57

由于ASP.NET MVC2,当您试图在没有附加信息的情况下返回Json结果时,您会得到一个错误:

此请求已被阻止,因为在GET请求中使用敏感信息时,可能会将其披露给第三方网站。

现在必须将属性JsonRequestBehavior设置为值AllowGet:

result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

我在一篇帖子上读到,这可以防止劫持。

我想知道Json.Net是否有类似的东西可以防止这种类型的攻击。

以下是我创建Json结果的代码:

  protected JsonNetResult JsonNet(object data)
  {
     JsonNetResult result = new JsonNetResult();
     result.Data = data;
     return result;
  }

如果你想知道我在哪里找到JsonNetResult,这里有一个链接。

非常感谢。

JsonRequestBehavior equivalent in Json.Net with Asp.Net Mvc

您不需要它,因为在您展示的自定义JsonNetResult中没有这样的测试。因此,如果使用get调用操作,您将永远不会得到像使用标准JsonResult那样的异常。

如果需要,可以在自定义JsonNetResult属性上实现完全相同的属性。

public class JsonNetResult : ActionResult
{
    public JsonNetResult()
    {
        SerializerSettings = new JsonSerializerSettings();
        JsonRequestBehavior = JsonRequestBehavior.DenyGet;
    }
    public JsonRequestBehavior JsonRequestBehavior { get; set; }
    ....
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        var httpMethod = context.HttpContext.Request.HttpMethod;
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && 
            string.Equals(httpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("You can't access this action with GET");
        }
        ...
    }
}

如果你想明确地允许这一特定操作:

protected ActionResult JsonNet(object data)
{
    JsonNetResult result = new JsonNetResult();
    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    result.Data = data;
    return result;
}