将额外的JSON对象添加到Web API响应

问题描述:

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

我的代码现在:

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

如果评论被顺利取出,我想送:

“状态”: “成功”

以及它已经作为JSON数组发送的评论列表。

“状态”: “失败”

如果评论列表为空。是否有可能将这个额外的名为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); 
    } 

您可以返回匿名对象与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 }); 
    } 
+0

检查编辑,将这项工作? – Dinuka

+0

我现在无法测试它,但我认为它会起作用,为什么不试一试呢? – adt

+0

是的,它的作品!谢谢:) – Dinuka

你可以试试这个

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; 
    }