Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
jacobsowles Avatar asked Sep 12 '26 15:09

jacobsowles


1 Answers

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.

like image 184
Nkosi Avatar answered Sep 15 '26 06:09

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!