Data models not showing up in HttpResponseMessage

前端 未结 1 1947
谎友^
谎友^ 2020-12-02 01:07

I\'m trying to make a simple API call from a .NET Core MVC application:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(\"http://loc         


        
相关标签:
1条回答
  • 2020-12-02 01:47

    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.

    0 讨论(0)
提交回复
热议问题