I need help for my project which consists of creating an e-commerce website. I am currently working on orders and when I do my controller (OrdersController) I cannot use "HttpResponseException" nor "Request.CreateResponse". How can I do to be able to use them? These are the comments in:
- GetOrder: throw new ...
- PostOrder: HttpResponseMessage message ... // Return response // return Request.Create ...
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ElevenCherryBackEnd.Entities;
using ElevenCherryBackEnd.Helpers;
namespace ElevenCherryBackEnd.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class OrdersController : ControllerBase
{
private readonly OrdersContext _context;
public OrdersController(OrdersContext context)
{
_context = context;
}
// GET: api/Orders
[HttpGet]
public IEnumerable<Order> GetOrders()
{
return _context.Orders.Where(o => o.Customer == User.Identity.Name);
}
// GET: api/Orders/5
[HttpGet("{id}")]
public OrderDTO GetOrder(int id)
{
Order order = _context.Orders.Include("OrderDetails.Product")
.First(o => o.Id == id && o.Customer == User.Identity.Name);
if (order == null)
{
//throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
return null;
}
return new OrderDTO()
{
Details = from d in order.OrderDetails
select new OrderDTO.Detail()
{
ProductID = d.Product.Id,
Product = d.Product.Name,
Price = d.Product.Price,
Quantity = d.Quantity
}
};
}
// POST: api/Orders
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Order>> PostOrder(OrderDTO dto)
{
if (ModelState.IsValid)
{
var order = new Order()
{
Customer = User.Identity.Name,
OrderDetails = (from item in dto.Details select new OrderDetail()
{ ProductId = item.ProductID, Quantity = item.Quantity }).ToList()
};
_context.Orders.Add(order);
_context.SaveChanges();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, order);
//return response;
return order;
}
//return Request.CreateResponse(HttpStatusCode.BadRequest);
return null;
}
}
}