I am stuck with web api testing between POSTMAN and Asp.Net Core Web Api.
It is likely that Web app responses only when it can model-binds from URL. However, it responses status 500 code every time it should model-binds from HTTP request body.
My codes are as below.
Web Api Controller code:
[ApiController]
[Route("api/[controller]")]
public class OrderController : ControllerBase
{
private IOrderRepository _orderRepo;
public OrderController(IOrderRepository repo) // Dependency Injection
{
_orderRepo = repo;
}
[HttpGet]
public IEnumerable<Order> Get() => _orderRepo.Orders;
[HttpGet("{id}")]
public Order Get(int id) => _orderRepo[id];
[HttpPost]
public Order Post([FromBody] Order order) => _orderRepo.Add(order);
Model Class Code:
public class Order
{
public int Id { get; set; } = 0;
public string ClientName { get; set; }
public string Menu { get; set; }
public int NoOfMenu { get; set; }
public Order(string clientName, string menuName, int noOfMenu)
{
ClientName = clientName;
Menu = menuName;
NoOfMenu = noOfMenu;
}
}
Repository's code for POST action method:
// deleted for brevity
private Dictionary<int, Order> _orderlist = new Dictionary<int, Order>();
public Order Add(Order newOrder)
{
if(newOrder.Id == 0)
{
int key = _orderlist.Count;
while(_orderlist.ContainsKey(key)) key++;
newOrder.Id = key;
}
_orderlist[newOrder.Id] = newOrder;
return newOrder;
}
in POSTMAN, Get request was successful.
This is when Get: api/Order/id
However, Post request returns Status 500.
Can anybody help for this situation?
I test your codes and reproduced your problem. You can add a parameterless constructor.
public class Order
{
public int Id { get; set; } = 0;
public string ClientName { get; set; }
public string Menu { get; set; }
public int NoOfMenu { get; set; }
public Order(string clientName, string menuName, int noOfMenu)
{
ClientName = clientName;
Menu = menuName;
NoOfMenu = noOfMenu;
}
public Order()
{
}
}