如何在执行webapi操作后在json中发送成功/失败响应?我有一个名为FundTransfer的函数,如何实现它像输出:如下所示
FundTransfer(string FromAccountNo, string ToAccountNo, decimal Amount,
string Remarks)
Output:
return: Success OR Fail with reason
string MsgCode: 00 (means success) OR 11 (means failure)
string Message: "Insufficient Balance ... or any other reason" (if fail,
there must be some reason in the Message")
当我调用api时,它会执行并在成功执行时发送 true
我的Webapi行动(现在)
[HttpPost]
[ActionName("transfer")]
public IHttpActionResult FundTransfer([FromBody] FundTransfer transfer)
{
var transferData = BusinessLayer.Api.AccountHolderApi
.FundTransfer(transfer);
return Ok(transferData);
}
业务层
public static bool FundTransfer(FundTransfer transferData)
{
return
DatabaseLayer.Api.AccountHolderApi.FundTransfer(transferData);
}
DatabaseLayer
public static bool FundTransfer(FundTransfer transferData)
{
string sql = @"SELECT * FROM sms.post_fund_transfer('" +
transferData.FromAccount + "','" +
transferData.ToAccount + "','" + transferData.Amount +
"','" + transferData.Statement + "')";
using (var command = new NpgsqlCommand(sql))
{
return DBOperations.ExecuteNonQuery(command);
}
}
我仍然在学习webapi并且确实找到了一些与回复消息相关的问题/答案,但无法通过。非常感谢。
谢谢。
答案 0 :(得分:1)
您可以创建一个包含响应数据类型的类
public class responseMsg
{
public class MsgCode { get; set; }
public class Message { get; set; }
}
然后在您的FundTransfer方法中使用它
public responseMsg FundTransfer(string FromAccountNo, string ToAccountNo, decimal Amount, string Remarks)
{
//implement logic and create a response
return new responseMsg { MsgCode = "11", Message="Insufficient Balance ..." };
}
然后在api方法中读取MsgCode并设置http响应代码
[HttpPost]
[ActionName("transfer")]
public IHttpActionResult FundTransfer([FromBody] FundTransfer transfer)
{
//call your logic which response with the responseMsg
var response = logic();
if(response.MsgCode == "11")
{
return Content(HttpStatusCode.BadRequest, response.Message);
}
else
{
return Ok(response.Message);
}
}