Return string from Web API .NET Core get operation
Asked Answered
M

1

6

I have a get operation that I want to return a string from. An example would be

"000875"

When I return this string from a controller in my Web API Controller in full .NET, it formats it like this:

{
  "Property": "000875"
}

When I return the string in my converted .NET Core Controller it returns this:

{
  "$id": "1",
  "$type": "System.Net.Http.HttpResponseMessage, System.Net.Http",
  "Version": "1.1",
  "Content": {
    "$id": "2",
    "$type": "System.Net.Http.StringContent, System.Net.Http",
    "Headers": [
      {
        "Key": "Content-Type",
        "Value": [
          "application/json; charset=utf-8"
        ]
      }
    ]
  },
  "StatusCode": "OK",
  "ReasonPhrase": "OK",
  "Headers": [],
  "TrailingHeaders": [],
  "RequestMessage": null,
  "IsSuccessStatusCode": true
}

It is interesting to note that the value is not even in there!

I am running some interesting JSON Serialization to make BreezeJs work with .NET Core. It is possible that it is the cause of this weirdness:

.AddNewtonsoftJson(opt =>
{
   // Let Breeze say how we serialize.  This adds in the Type and Id options the way breeze expects
   var jsonSerializerSettings = JsonSerializationFns.UpdateWithDefaults(opt.SerializerSettings);
   ......

I am hoping for a way to get strings through without all this mess. Can that be done?

Miso answered 3/12, 2019 at 0:53 Comment(1)
Can you please show us the API method code which contains the return line?Yugoslavia
T
11

I get the impression that the subject action definition returns HttpResponseMessage.

public HttpResponseMessage MyAction(....

HttpRequestMessage is no longer a first class citizen in asp.net-core framework and will be treated as a normal model and serialized.

That explains the JSON you are seeing with your controller

The syntax needs to be updated to return IActionResult derived responses

public IActionResult MyAction() {

    //...

    return Ok("000875");
}

ActionResult<T>

public ActionResult<string> MyAction() {

    //...
    if(somecondition)
        return NotFound();

    return "000875";
}

or the model itself.

public string MyAction() {

    //...

    return "000875";
}

Reference Controller action return types in ASP.NET Core Web API

Teryn answered 3/12, 2019 at 1:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.