Data models not showing up in HttpResponseMessage

ぃ、小莉子 提交于 2019-12-28 03:10:32

问题


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://localhost:49897");

    var response = client.GetAsync("some-route").Result;
    var dataString = response.Content.ReadAsStringAsync().Result; // Unexpected data here. See below.

    [...] // deserialize dataString
}

client.GetAsync(route) successfully hits an API action method, which ultimately does this:

public HttpResponseMessage Get([FromUri] BindingModel bindingModel)
{
    List<SomeModel> resultObjects;

    [...] // populate resultObjects with data

    return Request.CreateResponse(HttpStatusCode.OK, resultObjects, new JsonMediaTypeFormatter());
}

But dataString ends up equaling this:

"{\"version\":{\"major\":1,\"minor\":1,\"build\":-1,\"revision\":-1,\"majorRevision\":-1,\"minorRevision\":-1},\"content\":{\"objectType\":\"System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e\",\"formatter\":{\"indent\":false,\"serializerSettings\":{\"referenceLoopHandling\":0,\"missingMemberHandling\":0,\"objectCreationHandling\":0,\"nullValueHandling\":0,\"defaultValueHandling\":0,\"converters\":[],\"preserveReferencesHandling\":0,\"typeNameHandling\":0,\"metadataPropertyHandling\":0,\"typeNameAssemblyFormat\":0,\"typeNameAssemblyFormatHandling\":0,\"constructorHandling\":0,\"contractResolver\":null,\"equalityComparer\":null,\"referenceResolver\":null,\"referenceResolverProvider\":null,\"traceWriter\":null,\"binder\":null,\"serializationBinder\":null,\"error\":null,\"context\":{},\"dateFormatString\":\"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK\",\"maxDepth\":null,\"formatting\":0,\"dateFormatHandling\":0,\"dateTimeZoneHandling\":3,\"dateParseHandling\":1,\"floatFormatHandling\":0,\"floatParseHandling\":0,\"stringEscapeHandling\":0,\"culture\":{}}}}}"

Or, in JSON format:

{
    version: {
        major: 1,
        minor: 1,
        [...]
    },
    content: {
        objectType: "System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"
        formatter: {
            indent: false,
            serializerSettings: {
                [...]
            }
        }
    }
}

My list of models isn't in there at all.

What exactly is being returned, and why isn't my list of models in the response? I've looked at several online resources, and I seem to be doing things the same way as they show. This is a pretty bread-and-butter API call, so I'm not sure what's going on.


回答1:


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.



来源:https://stackoverflow.com/questions/45226019/data-models-not-showing-up-in-httpresponsemessage

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