【问题标题】:Adding an extra JSON Object to the Web API Response向 Web API 响应添加额外的 JSON 对象
【发布时间】:2015-10-09 06:35:53
【问题描述】:

我需要将一个额外的 JSON 对象附加到由 Web API 方法生成的 JSON 响应中。例如:

我现在的代码:

[Route("api/getcomnts")]
public IHttpActionResult GetCommentsForActivity(string actid)
{
       List<Comment> cmntList = CC.GetAllComments(actid);
       return Ok(cmntList);
}

如果成功检索到 cmets,我想发送:

“状态”:“成功”

连同它已经作为 JSON 数组发送的 cmets 列表。

“状态”:“失败”

如果 cmets 列表为 EMPTY。是否可以将这个名为 JSON 的额外 JSON 对象附加到我已经存在的方法中?

这将使我的客户端 Android 和 iOS 应用程序非常方便:)

编辑

或者对于这样的场景:

    [HttpGet]
    [Route("api/registeruser")]
    public IHttpActionResult RegisterUser(string name, string email, string password)
    {

        int stat = opl.ConfirmSignup(name, email, password);
        string status = "";
        if (stat == 0)
        {
            status = "fail";
        }
        else
        {
            status = "success";
        }
        return Ok(status);
    }

【问题讨论】:

    标签: asp.net json azure asp.net-web-api azure-mobile-services


    【解决方案1】:

    您可以使用 Web API 返回匿名对象。

        [Route("api/getcomnts")]
        public IHttpActionResult GetCommentsForActivity(string actid)
        {
               List<Comment> cmntList = CC.GetAllComments(actid);
               var success = cmntList.Count() > 0 ? "success" : "success";
               return Ok(new { List = cmntList, success } );
        }
    
    **EDIT:**
    
        [Route("api/getcomnts")]
        public IHttpActionResult GetCommentsForActivity(string actid)
        {
               List<Comment> cmntList = CC.GetAllComments(actid);
               string status = "";
               if(cmntList.Count()!=0)
               {
                    status = "success";
               }
               else
               {
                    status = "fail"; 
               }
               return Ok(new { List = cmntList, status } );
        }
    

    【讨论】:

    • 我现在无法测试它,但我认为它会起作用,为什么不试试呢?
    • 嘿伙计,它返回 "{"string":"success"}" 而不是 {"status":"success"}。 “地位”这个词不来了
    • new { List = cmntList, status = success } 你能试试吗?
    • 没有前面的例子有效,我在我的问题中编辑并发布了一个新方法。此方法只返回没有“状态”部分的“成功”。你能检查一下编辑吗? :)
    【解决方案2】:

    你可以试试这个

    public HttpResponseMessage Get(string actid)
        {
            //sample..
            if (value == true)
                return Request.CreateResponse(HttpStatusCode.OK, getStatus("success"), JsonMediaTypeFormatter.DefaultMediaType);
            else
                return Request.CreateResponse(HttpStatusCode.OK, getStatus("failed"), JsonMediaTypeFormatter.DefaultMediaType);
        }
    
        private object getStatus(string s)
        {
            var status = new { Status = s };
            return status;
        }
    

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多