Adding an additional JSON object in response to the web interface

I need to connect an additional JSON object to my JSON response generated by a Web API method. For example:

My code:

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

      

If the comments were successfully restored, I would like to submit:

"status": "Success"

along with the list of comments, which it already sends as a JSON array.

or

"status": "failure"

if the comment list is NULL. Is it possible to connect this additional JSON object named JSON to an already existing method?

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

EDIT

Or for a scenario like:

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

      

+3


source to share


2 answers


You can return an anonymous object using the 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 } );
    }

      

+1


source


You can try this



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

      

0


source







All Articles