【发布时间】:2018-08-10 22:27:44
【问题描述】:
目前,我的ApiControllers 正在返回 XML 作为响应,但对于单个方法,我想返回 JSON。即我无法进行全局更改以强制响应为 JSON。
public class CarController : ApiController
{
[System.Web.Mvc.Route("api/Player/videos")]
public HttpResponseMessage GetVideoMappings()
{
var model = new MyCarModel();
return model;
}
}
我尝试这样做,但似乎无法将我的模型正确转换为 JSON 字符串:
var jsonString = Json(model).ToString();
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
return response;
【问题讨论】:
-
尝试返回类型
JsonResult而不是HttpResponseMessage,那么你可以返回一个Json对象,像这样:return Json(model) -
试试这个ApiController.Ok你就做
return Ok(model) -
@RicardoPontual 是 System.Web.Mvc.JsonResult 吗?我收到了
Cannot implicitly convert type 'System.Web.Http.Results.JsonResult<MyCarModel>' to 'System.Web.Mvc.JsonResult' -
System.Web.Mvc.JsonResult,如果你的类继承自System.Web.Mvc.Controller,或者你可以维护HttpResponseMessage并使用return Request.CreateResponse(HttpStatusCode.OK, model)
标签: c# asp.net-mvc asp.net-web-api asp.net-web-api2 asp.net-apicontroller