2016-05-13 87 views
0

我處於嚴重的困境中。我用什麼樣的服務將對象轉換爲JSON?什麼是使C#MVC控制器響應JSON的最佳方式?


弗里斯特場景:

我用微軟的序列化,代碼將是這樣的:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public JsonResult Get(string param) 
    { 
     return Json(result); 
    } 

第二種情況:

我用的是Newtonsoft,示例代碼:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public string Get(string param) 
    { 
     return JsonConvert.SerializeObject(result); 
    } 

我該怎麼辦?誰更好,更安全還是更快?

我嘗試在文檔中找到響應,但我仍然有疑問。

+0

只是一個想法,你檢查了[ASP.NET Web API](http://www.asp.net/web-api)?它專爲此特定用例而設計,無需您序列化。我建議,因爲你的標題說「最簡單的方法」... –

回答

1

該框架的JsonResult適合於99%的時間。已經表明,JSON.NET更快,但序列化不是典型的瓶頸。所以除非你需要使用JSON.NET。順便說一下,您的第二種情況不會返回application/json內容,但text/html

1

以前的回答者提供了一個很好的觀點,但我可以根據我如何處理問題提供答案。

在我的控制器中,我有一個實際在文件中查找json的路由/函數,但您也可以使用Newtonsoft nuget包代碼序列化一個對象。

public ActionResult XData(string id) 
    { 
     string dir = WebConfigurationManager.AppSettings["X_Path"]; 

     //search for the file 
     if (Directory.Exists(dir) && System.IO.File.Exists(Path.Combine(dir, id, "X.json"))) 
     { 
      //read the file 
      string contents = System.IO.File.ReadAllText(Path.Combine(dir, id, "X.json")); 

      //return contents of the file as json 
      return Content(contents, "application/json"); 
     } 
     return new HttpNotFoundResult(); 
    } 
相關問題