yavg
yavg

Reputation: 3051

what is the best way to return a json in an Ok () (status 200) of an Api?

In ASP.NET Core Web API project, I am doing this to build a json style:

    {
        "ok": true,
        "error": {
            "message": "el valor Terror ya existe"
        }
    }

with this code:

 message = $"el valor {message} ya existe";
 var new_json= JsonConvert.SerializeObject(new { ok = true, error = new { message = message } });
 return Ok(new_json);

the json is returned as plain text. how can I make it return as a json?

Upvotes: 1

Views: 931

Answers (2)

CoolBots
CoolBots

Reputation: 4889

ASP.NET Core Web API framework auto-serializes the responses as JSON. So, you're manually serializing first - you get a string. That string gets serialized (as another string) - and sent over to the client... where you deserialize it... and get a string!

Remove the JsonConvert.SerializeObject() call, and just pass the JSON object (your Model, presumably) to the Ok() function:

message = $"el valor {message} ya existe";
var new_json = new { ok = true, error = new { message = message } };
return Ok(new_json);

Upvotes: 3

Caius Jard
Caius Jard

Reputation: 74680

Like this:

message = $"el valor {message} ya existe";
return Ok(new { 
  ok = true, 
  error = new { 
    message = message 
  } 
});

Upvotes: 0

Related Questions