OLDMONK
OLDMONK

Reputation: 382

How to send a success/failure message in json in web api?

How to send a success/failure response in json after execution of the webapi action?I have a function called FundTransfer, how to implement it like the output: given below

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

At the moment when i call the api it executes and sends true on successfull execution

My Webapi Action (Now)

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

        return Ok(transferData);
    }

Business Layer

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

I am still learning webapi and did find some questions/answers related to response messages but couldnt get through.any help appreciated.

Thank You.

Upvotes: 0

Views: 3455

Answers (1)

Marcus Höglund
Marcus Höglund

Reputation: 16856

You could create a class which holds the response data type

public class responseMsg
{
    public class MsgCode { get; set; }
    public class Message { get; set; }
}

Then use that in your FundTransfer method

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 ..." };
}

Then read the MsgCode in the api method and set the http response code

[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);
    }
}

Upvotes: 1

Related Questions