2015-07-20 65 views
3

我需要將附加的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); 
    } 

回答

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 }); 
    } 
+0

檢查編輯,將這項工作? – Dinuka

+0

我現在無法測試它,但我認爲它會起作用,爲什麼不試一試呢? – adt

+0

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

0

你可以試試這個

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