Search code examples
c#htmlasp.netasp.net-corerazor

Place order handler not working, redirects me to 404 error page, and the breakpoint doesn't get hit either, why?


[ValidateAntiForgeryToken]
public IActionResult OnPostPlaceOrder()
{
    try
    {
        if (!_userManager.UserIsGuest())
        {
            int? customerID = _customerManager.GetCustomerId();
            if (customerID.HasValue)
            {
                var rentalOrder = new RentalOrder
                {
                    CustomerID = customerID.Value,
                    RentalStartDate = DateTime.Now,
                    RentalEndDate = DateTime.Now.AddDays(7), 
                    TotalCost = _rentalOrderManager.CalculateTotalCost(Cart), 
                    Status = OrderStatus.Pending,
                    StartTime = TimeSpan.FromHours(8), 
                    EndTime = TimeSpan.FromHours(18) 
                };

                int orderId = _rentalOrderManager.PlaceOrder(Cart, rentalOrder);

                return RedirectToPage("/OrderConfirmation", new { orderId });
            }
        }

        return Page();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "An error occurred in OnPostPlaceOrder method");
        return RedirectToPage("/Error");
    }
}

public IActionResult OnPostRemoveFromCart(int ItemID)
{
    _cartManager.RemoveItemFromCart(Cart, ItemID);
    return RedirectToPage("/Cart");
}
<form method="post" asp-page-handler="PlaceOrder">
    <button type="submit" class="btn btn-primary">Place Order</button>
</form>
using BusinessLogicLayer;
using DataAccessLayer;
using SharedClassesLibrary;
using System.Text;

namespace WebApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

    }

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddScoped<DataAccess>();
            services.AddScoped<ICustomerRepository, CustomerRepository>();
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IUserManager, UserManager>();
            services.AddScoped<IGuestManager, GuestManager>();
            services.AddScoped<IRentalItemRepository, RentalItemRepository>();
            services.AddScoped<IRentalItemManager, RentalItemManager>();
            services.AddScoped<IRentalOrderManager, RentalOrderManager>();
            services.AddScoped<RentalOrderManager>();
            services.AddScoped<ICustomerManager, CustomerManager>();

            services.AddScoped<ICartRepository, CartRepository>();
            services.AddScoped<CartManager>();
            services.AddScoped<IRentalItemService, RentalItemService>();
            services.AddHttpContextAccessor();
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name = "CookieMonster";
                options.IdleTimeout = TimeSpan.FromMinutes(300);
            });
        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseSession();

            app.Use(async (context, next) =>
            {
                var userManager = context.RequestServices.GetRequiredService<IUserManager>();
                var httpContext = context;
                var guestManager = context.RequestServices.GetRequiredService<IGuestManager>(); 
                if (userManager.UserIsGuest() && !httpContext.Session.TryGetValue("GuestIdentifier", out byte[] sessionValue))
                {
                    var guestIdentifier = guestManager.GenerateNewGuestIdentifier();
                    httpContext.Session.Set("GuestIdentifier", Encoding.UTF8.GetBytes(guestIdentifier));
                }
                await next();
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapRazorPages();
            });

        }
    }
}

I tried to change the cshtml form code, and I expected successful redirection to the order confirmation page, so working functionality, or at least be able to debug the method, but it doesn't get hit either. Maybe I'm not noticing something really obvious. Help is highly appreciated. I've added the progam.cs code to it as well.


Solution

  • Make sure Razor files under the Pages folder like:

    enter image description here