Data models not showing up in HttpResponseMessage

本小妞迷上赌 提交于 2019-11-27 09:34:25
Nkosi

What exactly is being returned, and why isn't my list of models in the response?

What's being returned is a JSON-serialized version of your HttpResponseMessage, because while Web API 2 handles this type specially, ASP.NET Core web API does not.

To be precise, ASP.NET Core web API supports returning the following types:

  • IActionResult
  • ActionResult<T>
  • <any other type>

The first two are treated specially, but the third results in that type being JSON-serialized and returned, exactly as you saw.

In contrast, Web API 2 supports the following special return types:

  • void
  • HttpResponseMessage
  • IHttpActionResult
  • <any other type>

The correct solution is to update your code to use a custom IActionResult implementation instead of returning raw HttpResponseMessages. You may find this guide aids you in doing so - in particular, the Microsoft.AspNetCore.Mvc.WebApiCompatShim NuGet package has a ResponseMessageResult class that allows you to convert your Web API controller method from this:

public HttpResponseMessage Foo(Bar quux)
{
    return new BazHttpResponseMessage();
}

to this:

public IActionResult Foo(Bar quux)
{
    return new ResponseMessageResult(new BazHttpResponseMessage());
}

which should allow your current code to work as-is.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!