是否可以通过Web API返回json数据?

San*_*ndy 0 asp.net-mvc json asp.net-web-api

我有一个控制器动作,它返回一个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);

    }
Run Code Online (Sandbox Code Playgroud)

maa*_*nba 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您的客户端应指定他们想要的数据类型.如果指定了Accept:application/json标头,则Web API将返回JSON.接受:text/xml将产生XML.

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