Dinuka Jayasuriya Dinuka Jayasuriya - 1 month ago 10
ASP.NET (C#) Question

Adding an extra JSON Object to the Web API Response

I need to attach an extra JSON object to my JSON response generated by the Web API Method. For example:

My code now:

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


If the comments were successfully retrieved, I'd like to send:


"status":"success"


along with the comments list that it already sends as the JSON Array.

or


"status":"fail"


if the comments list is EMPTY. Is it possible to attach this extra JSON object named JSON to my already existing method?

This would make it very convenient for my client Android and iOS apps :)

EDIT

Or for a scenario such as this:

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

adt adt
Answer

You can return anonymous object with 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 } );
    }
Comments