Reputation: 61
I have created A cart controller and index view. When I access localhost/cart, I got 404 error. I do not know why it is showing 404. I have the same issue for product controller as well. I am getting 404 when accessing index page. In the product controller, I have added another method called ProductByCategory and related cshtml page. I can access to it.
I have created CartController as below.
namespace Ricebuddy.Controllers
{
public class CartController : Controller
{
private readonly RicebuddyContext context;
public CartController(RicebuddyContext context)
{
this.context = context;
}
// GET /cart
public IActionResult Index()
{
List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart") ?? new List<CartItem>();
CartViewModel cartVM = new CartViewModel
{
CartItems = cart,
GrandTotal = cart.Sum(x => x.Price * x.Quantity)
};
return View(cartVM);
}
In my Views>Cart>Index.cshtml, I have following codes.
@model Ricebuddy.Models.CartViewModel
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
@if (Model.CartItems.Count > 0)
{
<div>
<h4>CartViewModel</h4>
<hr />
<dl class="row">
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.GrandTotal)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.GrandTotal)
</dd>
</dl>
</div>
<div>
@Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
<a asp-action="Index">Back to List</a>
</div>
}
else
{
<h3 class="display-4 text-center">Your cart is empty.</h3>
}
My Startup.cs got the following routes.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"pages",
"{slug?}",
defaults: new { controller = "Pages", action = "Page" }
);
endpoints.MapControllerRoute(
"products",
"products/{categorySlug}",
defaults: new { controller = "Products", action = "ProductsByCategory" }
);
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Upvotes: 1
Views: 47
Reputation: 61
That's being picked up by your "pages" route? Like how could it know that it's meant to hit "default" instead of "pages" ?
as mentioned in the comment.
So I moved pages endpoint to below default endpoints. It works and not giving me 404 when I am accessing index for both cart and product controllers.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"products",
"products/{categorySlug}",
defaults: new { controller = "Products", action = "ProductsByCategory" }
);
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
"pages",
"{slug?}",
defaults: new { controller = "Pages", action = "Page" }
);
});
Upvotes: 1