2013-03-13 61 views
0

我有一個控制器操作返回一個JSON數據。它可以通過getJSON方法輕鬆訪問。但我希望通過Web API檢索JSON數據。是否可以通過web API返回json數據?

我的控制器代碼是

public ActionResult GetProfile(string profileName) 
    { 
     var profileDataService = new BokingEngine.MasterDataService.GetProfileDataService(); 
     var request = new ProfileSearchCriteria { Name = profileName }; 
     var profileDetails = profileDataService.GetList(request); 
     return Json(profileDetails, JsonRequestBehavior.AllowGet); 

    } 
+0

[檢查此鏈接](http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using -chrome)和[鏈接2](http://www.hanselman.com/blog/OneASPNETMakingJSONWebAPIsWithASPNETMVC4BetaAndASPNETWebAPI.aspx) – 2013-03-13 06:05:05

+0

順便說一句你的代碼使用的是ASP.NET MVC,而不是ASP.NET Web API。您是否嘗試將MVC的代碼轉換爲Web API或其他東西? – Eilon 2013-03-13 06:14:11

回答

5

在網頁API,這將是你的行動:

public class ProfileController : ApiController { 
    public ProfileData Get(string profileName) 
    { 
     var profileDataService = new BokingEngine.MasterDataService.GetProfileDataService(); 
     var request = new ProfileSearchCriteria { Name = profileName }; 
     var profileDetails = profileDataService.GetList(request); 
     return profileDetails; 
    } 
} 

那麼你的客戶端應該指定他們想要的數據類型。如果指定了Accept:application/json標頭,則Web API將返回JSON。接受:text/xml將產生XML。

更多信息:http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

+0

它不會在我的情況下工作,因爲'profileDetails'和'ProfileData'是一個模型類。我不能返回課堂上課 – Sandy 2013-03-13 09:01:26

0

您的ActionResult更改爲JsonResult所以它返回JSON。如果你想使Web API特定,你應該創建一個繼承ApiController的控制器。

相關問題