Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

c# - Data models not showing up in HttpResponseMessage

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...