0

I have a controller action which return a JSON data. It can be easily accessible through a getJSON method. But I want that JSON data to be retrieved through web API.

My controller code is

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);

    }
j0k
  • 22,600
  • 28
  • 79
  • 90
Sandy
  • 2,429
  • 7
  • 33
  • 63
  • [Check this link](http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome) and [Link 2](http://www.hanselman.com/blog/OneASPNETMakingJSONWebAPIsWithASPNETMVC4BetaAndASPNETWebAPI.aspx) – K D Mar 13 '13 at 06:05
  • BTW your code is using ASP.NET MVC, not ASP.NET Web API. Are you trying to convert the code from MVC to Web API or something else? – Eilon Mar 13 '13 at 06:14

2 Answers2

5

In Web API, this would be your action:

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;
    }
}

Then your client should specify the data type they want. If an Accept: application/json header is specified, Web API returns JSON. Accept: text/xml will yield XML.

More info: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

maartenba
  • 3,344
  • 18
  • 31
  • It wont work in my case as 'profileDetails' and 'ProfileData' is a model class. I cant return list to class – Sandy Mar 13 '13 at 09:01
0

Change your ActionResult to JsonResult so it returns Json. If you want to make Web API specific, you should create a Controller that inherits ApiController.

LockTar
  • 5,364
  • 3
  • 46
  • 72