2012-03-16 72 views
2

由於ASP.NET MVC2,當您嘗試不帶附加信息返回JSON結果,你會得到一個錯誤:JsonRequestBehavior相當於Json.Net與Asp.Net的mvc

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request.

現在必須設置屬性JsonRequestBehavior爲值AllowGet

result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 

read on a post這妨礙劫持。

我想知道是否有與Json.Net等效防止這種類型的攻擊。

這裏是我的代碼來創建JSON結果:

protected JsonNetResult JsonNet(object data) 
    { 
    JsonNetResult result = new JsonNetResult(); 

    result.Data = data; 

    return result; 
    } 

如果你想知道我找到了JsonNetResult,here is a link

非常感謝。

回答

4

你並不需要它,因爲你已經證明沒有這樣的測試自定義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; 
} 
+0

謝謝達林。對於我來說,從StackOverflow最強大的貢獻者之一獲得答案是我的榮幸。 – Samuel 2012-03-16 14:04:58