How to send two objects as response message and response code in web api
I want to send a response message like this
{"message_code": 00, "message": "Success"}
The class of my answer
public class ResponseMessage
{
public string MessageCode { get; set; }
public string Message { get; set; }
}
And my message method
public ResponseMessage Message(FundTransfer transfer)
{
var checkBalance =
BusinessLayer.Api.AccountHolderApi.GetBalance(transfer.FromAccount);
if (checkBalance.Balance.ToDecimal() < transfer.Amount)
{
return new ResponseMessage
{
MessageCode = "22",
Message = "Insufficient Balance"
};
}
else
{
var transferData = BusinessLayer.Api.AccountHolderApi
.FundTransfer(transfer);
if (transferData == true)
{
return new ResponseMessage { MessageCode = "00", Message = "Success" };
}
else
{
return new ResponseMessage { MessageCode = "11", Message = "Some Error" };
}
}
}
And my API method
[HttpPost]
[ActionName("transfer")]
public IHttpActionResult FundTransfer([FromBody] FundTransfer transfer)
{
var response = Message(transfer);
if (response.MessageCode == "11")
{
return Content(HttpStatusCode.BadRequest, response.Message);
}
else
{
return Ok(response.Message);
}
}
Now, for example, when transferData == true
in my method Message()
I only get the value of the message object as "Success", since in my return content I am returning response.Message
. I want to receive the response in JSON as
{"message_code": 00, "message": "Success"}
instead "success"
The web API is currently being explored.
source to share
Refactor API Model return method instead of message property
[HttpPost]
[ActionName("transfer")]
public IHttpActionResult FundTransfer([FromBody] FundTransfer transfer) {
var response = Message(transfer);
if (response.MessageCode == "11") {
return Content(HttpStatusCode.BadRequest, response);
} else {
return Ok(response);
}
}
Also to get a message like this
{"message_code": "00", "message": "Success"}
ResponseMessage
Class refactor via JSON property attribute ...
public class ResponseMessage {
[JsonProperty("message_code")]
public string MessageCode { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
Or build the model anonymously
[HttpPost]
[ActionName("transfer")]
public IHttpActionResult FundTransfer([FromBody] FundTransfer transfer) {
var response = Message(transfer);
var model = new {
message_code = response.MessageCode,
message = response.Message
};
if (response.MessageCode == "11") {
return Content(HttpStatusCode.BadRequest, model);
} else {
return Ok(model);
}
}
source to share