如何在ApiController中为单个方法返回JSON?

coo*_*eze 14 c# asp.net-mvc asp.net-web-api asp.net-apicontroller asp.net-web-api2

目前,我ApiController正在返回XML作为响应,但对于单个方法,我想返回JSON.即我无法进行全局更改以强制响应为JSON.

public class CarController : ApiController
{  
    [System.Web.Mvc.Route("api/Player/videos")]
    public HttpResponseMessage GetVideoMappings()
    {
        var model = new MyCarModel();    
        return model;
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试这样做,但似乎无法正确地将我的模型转换为JSON字符串:

var jsonString = Json(model).ToString();    
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
return response;
Run Code Online (Sandbox Code Playgroud)

Ash*_*man 22

如果您无法进行全局更改以强制响应为JSON,请尝试:

[Route("api/Player/videos")]
public HttpResponseMessage GetVideoMappings()
{
    var model = new MyCarModel();
    return Request.CreateResponse(HttpStatusCode.OK,model,Configuration.Formatters.JsonFormatter);
}
Run Code Online (Sandbox Code Playgroud)

要么

[Route("api/Player/videos")]
public IHttpActionResult GetVideoMappings()
{
    var model = new MyCarModel();
    return Json(model);    
}
Run Code Online (Sandbox Code Playgroud)

如果您想全局更改,请先转到YourProject/App_Start/WebApiConfig.cs并添加:

config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(
config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"));
Run Code Online (Sandbox Code Playgroud)

Register方法的底部.

然后尝试:

[Route("api/Player/videos")]
public IHttpActionResult GetVideoMappings()
{
    var model = new MyCarModel();
    return Ok(model);    
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*Ali 5

尝试这个ApiController.Ok

您只需将return Ok(model)返回类型更改为IHttpActionResult.

例子:

public class CarController : ApiController
{
    [System.Web.Mvc.Route("api/Player/videos")]
    public IHttpActionResult GetVideoMappings()
    {
        var model = new MyCarModel();
        return Ok(model);
    }
}
Run Code Online (Sandbox Code Playgroud)


ani*_*ina 5

因为调用者正在请求 XML,所以返回 XML 而不是 JSON。可以使用过滤器将返回的格式强制为 JSON,该过滤器添加您需要的标头并让 MVC 解析 JSON。

public class AcceptHeaderJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        actionContext.Request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用此属性装饰要强制 JSON 响应的方法,并保持与任何其他方法相同的全局 JSON 配置和序列化。