2017-06-14 65 views
0

如何將的WebAPI行動執行後發送成功/失敗響應的JSON我有一個名爲FundTransfer功能,如何實現它像輸出:下面如何在web api中發送json中的成功/失敗消息? ?

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") 

給出。在那一刻,我稱它爲執行和全成執行發送真正

我的WebAPI行動(現在)

[HttpPost] 
    [ActionName("transfer")] 
    public IHttpActionResult FundTransfer([FromBody] FundTransfer transfer) 
    { 
     var transferData = BusinessLayer.Api.AccountHolderApi 
      .FundTransfer(transfer); 

     return Ok(transferData); 
    } 
的API

業務層

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並沒有找到相關的響應消息的一些問題/答案,但不可能得到讚賞through.any幫助。

謝謝。

+1

我希望我不使用你的公司與該SQL注射:( – ATerry

+0

@ATerry S ire,沒有公司,學生,學習..但不會傷害,如果你分享和啓發我的SQL注入的事情?請。 – OLDMONK

+1

您正在傳遞一個命令到數據庫作爲SQL,你建立的SQL字符串使用未經清理的用戶參數。所以如果我要例如傳入「'); drop database sms;」進入FromAccount。告別你的短信數據庫。始終使用參數。 「從sms.post_fund_transfer(@ param1,@ param2,@ param3)中選擇*」。然後對每個參數使用新參數(「param1」,transferData.FromAccount),並對performtenonquery使用重載來分別傳遞查詢和參數,而不是手動注入。我的例子可能會有點偏差,我不再使用sql。 – ATerry

回答

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); 
    } 
} 
相關問題