Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return string from Web API .NET Core get operation

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?

like image 267
Vaccano Avatar asked Dec 03 '19 00:12

Vaccano


People also ask

What is the best way to define a return type of an Web API core action method?

Some common return types in this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200). Alternatively, convenience methods in the ControllerBase class can be used to return ActionResult types from an action.


1 Answers

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

like image 183
Nkosi Avatar answered Oct 12 '22 20:10

Nkosi