我有一个控制器动作,它返回一个JSON数据。可以通过getJSON方法轻松访问它。但我希望通过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 :(得分:5)
在Web 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
答案 1 :(得分:0)
将ActionResult更改为JsonResult,以便返回Json。如果要特定于Web API,则应创建一个继承ApiController的Controller。