简体   繁体   English

在 Api 的 Ok ()(状态 200)中返回 json 的最佳方法是什么?

[英]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.

相关问题 尽管状态为200 OK,为什么AJAX JSON响应仍失败? - Why is AJAX JSON response failing despite 200 OK status? 如果状态码不等于 200 OK 使用 Polly 重试 api 请求 - Use Polly to retry api request if the status code is not equal to 200 OK 未经授权的消息,状态为200 OK - Unauthorized Message,Status 200 OK ajax发布formdata错误状态200 OK - ajax posting formdata error status 200 OK JQuery AJAX,错误状态代码:200,状态文本:parserorro | 好 - JQuery AJAX, Error Status code: 200, Status Text: parserorro | OK 更新状态栏消息的最佳方法是什么? - what is the best way to update status bar message? Web API返回什么状态代码? - What status code to return in web api? C#-创建将运行存储过程然后返回以json格式提取的数据的Web服务的最佳方法是什么? - C# - What is the best way to create a web service that will run a stored procedure and then return the data fetched in a json format? "返回已完成任务的最佳方式是什么?" - What is the best way to return completed Task? 为什么我的 Web api 在使用 WebClient 类时返回状态代码 401,而在使用 HttpWebResponse 时返回状态代码 200? - Why my web api return Status code 401 when i use WebClient class and Status code 200 when i use HttpWebResponse?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM