Pankaj
Pankaj

Reputation: 4505

Customise WebAPI response like Status, Data, message formate

How can i customise WebAPI 2 response like status, data, message in JSON format

Successful request:

{
  "status": "success",
  "data": {
    /* Application-specific data would go here. */
  },
  "message": null /* Or optional success message */
}

Failed request:

{
  "status": "error",
  "data": null, /* or optional error payload */
  "message": "Error xyz has occurred"
}

Upvotes: -1

Views: 592

Answers (1)

Jose Francis
Jose Francis

Reputation: 960

Define a new class like :

public class ResponseDto
{
    public string status { get; set; }

    public dynamic data { get; set; }

    public string message { get; set; }
}

and then populate the properties with respective values and do :

var response = new ResponseDto()
{
    response.status = " ",
    response.data = obj,
    response.message = " "
}

and then from the controller method(API),

return response;

Your JSON formatter will then convert the response object into JSON string.

Upvotes: 1

Related Questions