如何在web api中发送两个对象作为响应消息和响应代码

时间:2017-06-15 12:28:53

标签: c# asp.net-web-api

我想发送像这样的回复消息

{"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。

1 个答案:

答案 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);
    }
}