I'm pretty new to asp and c# and I have a couple of concerns with the security of the code I have written (shown below). Basically all it does is allow you to enter a quantity before you add the item to your cart using a razor form.
Every example I see uses validation on input fields, like:
[Required]
[DataType(DataType.EmailAddress)]
Is that sort of validation (or any other) necessary in this case, or is my form secure enough because the controller requires the input of the product id and the quantity, both of which are limited to integers? Also, is there anything else that I should be concerned about with this form, like Javascript injection?
Thanks for your help!
The view has a razor input form:
@using ( Html.BeginForm( "AddToCart", "Cart" ) )
{
@Html.HiddenFor(_ => item .ProductID)
@Html.TextBoxFor(_=> item.Quantity)
<input type="submit" value="+ Add to cart" />
}
The form is posted to the AddToCart action of the CartController:
[HttpPost]
public ActionResult AddToCart(int id, int quantity)
{
// Retriebe the product from the database
var addedProduct = storeDB.Products
.Single(product => product.ProductId == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduct, quantity);
//Go back to the main store page for more shopping
return RedirectToAction("Index");
}
And here is the AddToCart method:
public void AddToCart(Product product, int quantity)
{
//Get the matching cart and album instances
var cartItem = storeDB.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.ProductId == product.ProductId);
if (cartItem == null)
{
// Create a new cart item if no cart exists
cartItem = new Cart
{
ProductId = product.ProductId,
CartId = ShoppingCartId,
Count = quantity,
DateCreated = DateTime.Now
};
storeDB.Carts.Add(cartItem);
}
else
{
// If the item does exist in the car,
// than add one to the quantity
var newCount = cartItem.Count + quantity;
cartItem.Count = newCount;
}
// Save changes
storeDB.SaveChanges();
}
Thanks again for your help!