我想发送像这样的回复消息
{"message_code": 00, "message": "Success"}
我的回复消息类
public class ResponseMessage
{
public string MessageCode { get; set; }
public string Message { get; set; }
}
我的留言方法
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" };
}
}
}
我的API方法
[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);
}
}
现在举例来说,当transferData == true
方法中的Message()
我只获得消息对象值为“成功”时,因为在我的返回内容中,我将返回response.Message
。我希望以JSON的形式获得响应
{"message_code": 00, "message": "Success"}
而不只是"success"
目前正在学习Web API。
答案 0 :(得分:3)
Refactor API方法返回模型而不仅仅是消息属性
[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);
}
}
还要收到这样的消息
{"message_code": "00", "message": "Success"}
通过JSON属性属性重构ResponseMessage
类...
public class ResponseMessage {
[JsonProperty("message_code")]
public string MessageCode { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
或匿名构建模型
[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);
}
}