Napoleon
Napoleon

Reputation: 388

Route homepage to Index inside Areas?

I want to use Areas for my RazorPage 3.1 Core project. However, I can't seem to redirect the homepage from http://localhost:<port> to http://localhost:<port>/Default/Index and the moment I use Areas and move my Pages folder into the Areas/Default/Pages I get an obvious 404 at my homepage. Every time I launch the project I get a 404 now for the homepage.

Or am I supposed to have 1 Pages folder outside of the Areas folder with the index as seen in the image below? That would be weird.

enter image description here

I tried everything I could find but I can't figure it out. I think it must be set somewhere in the Startup.cs:

            services.AddMvc().AddRazorPagesOptions(options =>
        {
            options.Conventions.AddPageRoute("/Default/Index", ""); // Or something?
        });

and:

public IActionResult Get()
{
    return RedirectToAction("Default/Index");
}

This didn't work for me:

Upvotes: 3

Views: 830

Answers (1)

Fei Han
Fei Han

Reputation: 27815

Route homepage to Index inside Areas

It seems that you'd like to display index page under Default area folder while user access at the root URL of your website.

To achieve the requirement, you can try to do URL rewrite operation like below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.Use(async (context, next) =>
    {
        if (context.Request.Path=="/")
        {
            context.Request.Path = "/Default/Index";
        }

        await next.Invoke();
    });

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

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

Test Result

enter image description here

Upvotes: 3

Related Questions