Reputation: 382
How to post parameter to a body and get the object in a list? IO am able to retrieve the data using this post method in my controller with parameter appended to the URI
Accounts controller:
[HttpPost]
[ActionName("mini")]
public List<MiniStatement> GetMiniStatement(string accountNumber)
{
var miniState = BusinessLayer.Api.AccountHolderApi.GetMiniStatement(accountNumber);
return miniState.ToList();
}
But how do I pass the parameter [FromBody]
and retrieve the data in a list?
MiniStatement class:
public class MiniStatement
{
public string AccountNumber { get; set; }
public string TranDate { get; set; }
public string Trans { get; set; }
public decimal Amount { get; set; }
}
GetMiniStatement
method in DB layer:
public static List<MiniStatement> GetMiniStatement(string accountNumber)
{
List<MiniStatement> resultList = new List<MiniStatement>();
using (var conn = new NpgsqlConnection("Server=localhost;UserId = postgres; " + "Password = pes; Database = pmc;"))
{
conn.Open();
using (var command = new NpgsqlCommand("SELECT * FROM sms.dep_mini_statement(@AccountNumber);", conn))
{
command.Parameters.AddWithValue("@AccountNumber", accountNumber);
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
var result = new MiniStatement
{
AccountNumber = accountNumber,
TranDate = (string)dr[0],
Trans = (string)dr[1],
Amount = (decimal)dr[2]
};
resultList.Add(result);
}
}
}
}
return resultList;
}
And the Route
config.Routes.MapHttpRoute("MobileBankingApi", "v1/{controller}/{action}");
Upvotes: 0
Views: 5174
Reputation: 16801
If you posting data as json you could populate the AccountNumber in an object as this
{ "AccountNumber": "23" }
Then add the [FromBody] in the controller method as this
[HttpPost]
[ActionName("mini")]
public List<MiniStatement> GetMiniStatement([FromBody] MiniStatement state)
{
var miniState = BusinessLayer.Api.AccountHolderApi.GetMiniStatement(state.AccountNumber);
return miniState;
}
Also, as the BusinessLayer.Api.AccountHolderApi.GetMiniStatement() returns a list you can just pass the response as is
Upvotes: 1
Reputation: 2461
So basically you can do the below.
Create a model class in your api.
public class Account
{
string AccountNumber{get;set;}
}
Then take it in your webapi method.
[HttpPost]
[ActionName("mini")]
public IActionResult GetMiniStatement([FromBody]Account account)
{
var miniState = BusinessLayer.Api.AccountHolderApi.GetMiniStatement(account.AccountNumber);
return new ObjectResult(miniState.ToList());
}
your request body should look like this.
{
"AccountNumber":"someNUmber"
}
Let me know if this helps.
Upvotes: 1