[英]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:在 ASP.NET Core Web API 项目中,我这样做是为了构建一个 json 样式:
{
"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. json 以纯文本形式返回。 how can I make it return as a json?
我怎样才能让它作为 json 返回?
ASP.NET Core Web API framework auto-serializes the responses as JSON. So, you're manually serializing first - you get a string
. ASP.NET 核心 Web API 框架将响应自动序列化为 JSON。因此,您首先要手动序列化 - 您会得到一个
string
。 That string gets serialized (as another string
) - and sent over to the client... where you deserialize it... and get a string
!该字符串被序列化(作为另一个
string
) - 并发送到客户端......在那里你反序列化它......并获得一个string
!
Remove the JsonConvert.SerializeObject()
call, and just pass the JSON object (your Model , presumably) to the Ok()
function:删除
JsonConvert.SerializeObject()
调用,然后将 JSON object(大概是您的Model )传递给Ok()
function:
message = $"el valor {message} ya existe";
var new_json = new { ok = true, error = new { message = message } };
return Ok(new_json);
Like this:像这样:
message = $"el valor {message} ya existe";
return Ok(new {
ok = true,
error = new {
message = message
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.