Change a default Homepage in ASP.NET Core Razor Pages

wire_jp 201 Reputation points
2021-01-15T01:02:32.04+00:00

Hello,

I am creating an ASP.NET Core Razor Pages website, where the planned layout of the website will be the following navigation menu structure: - Home | About Us | Services | Login | Contact Us. I have developed the Login webpage and. At present, when a user the builds the solution, it loads to a Login webpage. The user will then use a login & password to login to the Product Services webpage. I would like to change the default landing page so that the solution build loads to a "Home" (the default homepage) instead of the Login webpage.
In the Pages Folder, I created a Home Folder which contain the razor pages Index.cshtml and Index.cshtml.cs. In the Index.cshtml, I changed line 1 from:-

@Anonymous

to

@Anonymous "/Homepage"

and in the Startup.cs file, I added the followed code:-

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddMvc().AddRazorPagesOptions(options =>  
    {  
        options.Conventions.AddPageRoute("/Home/Index", "");  
    });  
}  

In the _Layout.cshtml file, the following code is found: -

<body>  
    <nav class="navbar navbar-inverse navbar-fixed-top">  
        <div class="container">  
            <div class="navbar-header">  
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
                    <span class="sr-only">Toggle navigation</span>  
                    <span class="icon-bar"></span>  
                    <span class="icon-bar"></span>  
                    <span class="icon-bar"></span>  
                </button>  
                <a asp-page="/Index" class="navbar-brand">Goods Store</a>  
            </div>  
            <div class="navbar-collapse collapse">  
                <ul class="nav navbar-nav">                     
                    <li><a asp-page="/Login/Index">Login</a></li>  
                    <li><a asp-page="/About">About</a></li>  
                    <li><a asp-page="/Service 1/Index">Service 1</a></li>  
                    <li><a asp-page="/Service 2/Index">Service 2</a></li>  
                </ul>  
            </div>  
        </div>  
    </nav>  
</body>  

However, when I build the solution, and I enter the Home url address: https://localhost:44370/Home/Index

, I see the following error message:

This localhost page can’t be foundNo webpage was found for the web address: https://localhost:44370/Home/Index
HTTP ERROR 404

Any assistance will be greatly appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,059 questions
0 comments No comments
{count} votes

Accepted answer
  1. jabm 76 Reputation points
    2021-09-17T22:25:45.283+00:00

    Hi, @wire_jp .

    You are using Net Core security and you must have a "FallbackPolicy" that makes you need a authenticated user to browse your site pages.

    You must add the [AllowAnonymous] tag to the the razor pages clases to allow browse some of these pages, that you want ,without login.

    [AllowAnonymous]  
    public class IndexModel : PageModel  
    

    I hope you fix the issue with this, if not, please let me know.

    Great day.

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. wire_jp 201 Reputation points
    2021-09-18T11:11:30.103+00:00

    Hi @jabm ,

    Thank you for your reply. It helped to fix my problem.

    Have a great day.

    1 person found this answer helpful.

  2. Michael Wang-MSFT 1,051 Reputation points
    2021-01-15T08:36:25.793+00:00

    Hi, @wire_jp ,

    You already se the @Anonymous directive to specify route "/Homepage" to this Index page. But added route ""/Home/Index"" in RazorPagesOptions. The details is described from this article.

    So you could change @page "/Homepage" to @page "/Home/Index"
    or
    options.Conventions.AddPageRoute("/Homepage", "");

    ----
    If the answer doesn’t solve your issue, please provide more details of error that will help us track down what’s happening.
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Michael Wang

    0 comments No comments

  3. wire_jp 201 Reputation points
    2021-01-16T18:08:17.423+00:00

    Hi, @Michael Wang-MSFT , thank you for your response. I applied your solution but I still received the error message.

    Under the Pages Folder, the full code for the Index.cshtml file of the Home folder is shown below:-

    @page "/Home/Index"  
    @model GoodStore.Pages.Home.IndexModel  
    @{  
        ViewData["Title"] = "Home";  
    }  
      
    <div class="container">  
        <div class="row">  
            <div class="col">  
                <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">  
                    <ol class="carousel-indicators">  
                        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>  
                        <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>  
                        <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>  
                         
                    </ol>  
                    <div class="carousel-inner">  
                        <div class="carousel-item active">  
                            <img class="d-block w-100" src="~/images/banner/banner1_1920px_x_948px.png" alt="First slide">  
                        </div>  
                        <div class="carousel-item">  
                            <img class="d-block w-100" src="~/images/banner/banner2_1920px_x_948px.png" alt="Second slide">  
                        </div>                     
                        <div class="carousel-item">  
                            <img class="d-block w-100" src="~/images/banner/banner4_1920px_x_948px.png" alt="Third slide">  
                        </div>  
                    </div>  
                    <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">  
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>  
                        <span class="sr-only">Previous</span>  
                    </a>  
                    <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">  
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>  
                        <span class="sr-only">Next</span>  
                    </a>  
                </div>  
            </div>  
      
        </div>  
    </div>  
    

    The full code for ConfigureServices(IServiceCollection services in the Startup.cs file is shown below:

            public void ConfigureServices(IServiceCollection services)  
            {  
                // setting up the Homepage as the landing page  
                services.AddMvc().AddRazorPagesOptions(options =>  
                {  
                    options.Conventions.AddPageRoute("/Home/Index", "");  
                });  
                // ----------------------------------------------            
                services.AddMvc();  
      
                services.Configure<CookiePolicyOptions>(options =>  
                {  
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.  
                    options.CheckConsentNeeded = context => true;  
                    options.MinimumSameSitePolicy = SameSiteMode.None;  
                });                     
      
                //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);  
                services.AddRazorPages().AddMvcOptions(options => options.EnableEndpointRouting = false);  
      
                services.AddDbContextPool<GoodStorageContext>(options =>  
                        options.UseSqlServer(Configuration.GetConnectionString("GoodStorageContext")));  
      
                services.AddDistributedMemoryCache();  
      
                services.AddSession(options =>  
                {  
                    options.IdleTimeout = TimeSpan.FromSeconds(1500);  
                    options.Cookie.HttpOnly = true;  
                    options.Cookie.IsEssential = true;  
                });  
      
      
            }  
    

    In the _Layout.cshtml file, the following code is found: -

     <body>  
         <div id="page">  
            <header>  
                <p class="site-title"><a href="~/">Goods Store</a></p>  
                <nav>  
                    <ul>  
                        <li><a href="~/">Home</a></li>  
                        <li><a href="~/AboutUs">About Us</a></li>  
                    </ul>  
                </nav>  
            </header>  
         <nav class="navbar navbar-inverse navbar-fixed-top">  
                <div class="container">  
                 <div class="navbar-header">  
                     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
                         <span class="sr-only">Toggle navigation</span>  
                         <span class="icon-bar"></span>  
                         <span class="icon-bar"></span>  
                         <span class="icon-bar"></span>  
                     </button>  
                     <a asp-page="/Index" class="navbar-brand">Goods Store</a>  
                 </div>  
                 <div class="navbar-collapse collapse">  
                     <ul class="nav navbar-nav">                     
                         <li><a asp-page="/Login/Index">Login</a></li>  
                         <li><a asp-page="/About">About</a></li>  
                         <li><a asp-page="/Service 1/Index">Service 1</a></li>  
                         <li><a asp-page="/Service 2/Index">Service 2</a></li>  
                     </ul>  
                 </div>  
             </div>  
         </nav>  
     </body>  
      
       <div class="container body-content">  
                @RenderBody()  
                <hr />  
                <footer>  
                    <p>&copy; 2021 – Goods Store</p>  
                </footer>  
            </div>  
        </div>  
    

    the original default index.cshtml file is shown below:-

    @page  
    @model IndexModel  
    @{  
        ViewData["Title"] = "Home page";  
    }  
      
    <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="6000">  
        <ol class="carousel-indicators">  
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>  
            <li data-target="#myCarousel" data-slide-to="1"></li>  
            <li data-target="#myCarousel" data-slide-to="2"></li>  
        </ol>  
        <div class="carousel-inner" role="listbox">  
            <div class="item active">  
                <img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" />  
                <div class="carousel-caption" role="option">  
                    <p>  
                        Learn how to build ASP.NET apps that can run anywhere.  
                        <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525028&clcid=0x409">  
                            Learn More  
                        </a>  
                    </p>  
                </div>  
            </div>  
            <div class="item">  
                <img src="~/images/banner2.svg" alt="Visual Studio" class="img-responsive" />  
                <div class="carousel-caption" role="option">  
                    <p>  
                        There are powerful new features in Visual Studio for building modern web apps.  
                        <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525030&clcid=0x409">  
                            Learn More  
                        </a>  
                    </p>  
                </div>  
            </div>  
            <div class="item">  
                <img src="~/images/banner3.svg" alt="Microsoft Azure" class="img-responsive" />  
                <div class="carousel-caption" role="option">  
                    <p>  
                        Learn how Microsoft's Azure cloud platform allows you to build, deploy, and scale web apps.  
                        <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525027&clcid=0x409">  
                            Learn More  
                        </a>  
                    </p>  
                </div>  
            </div>  
        </div>  
        <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">  
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>  
            <span class="sr-only">Previous</span>  
        </a>  
        <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">  
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>  
            <span class="sr-only">Next</span>  
        </a>  
    </div>  
      
    <div class="row">  
        <div class="col-md-3">  
            <h2>Application uses</h2>  
            <ul>  
                <li>Sample pages using ASP.NET Core Razor Pages</li>  
                <li>Theming using <a href="https://go.microsoft.com/fwlink/?LinkID=398939">Bootstrap</a></li>  
            </ul>  
        </div>  
        <div class="col-md-3">  
            <h2>How to</h2>  
            <ul>  
                <li><a href="https://go.microsoft.com/fwlink/?linkid=852130">Working with Razor Pages.</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=699315">Manage User Secrets using Secret Manager.</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=699316">Use logging to log a message.</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=699317">Add packages using NuGet.</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=699319">Target development, staging or production environment.</a></li>  
            </ul>  
        </div>  
        <div class="col-md-3">  
            <h2>Overview</h2>  
            <ul>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=518008">Conceptual overview of what is ASP.NET Core</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=699320">Fundamentals of ASP.NET Core such as Startup and middleware.</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=398602">Working with Data</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkId=398603">Security</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkID=699321">Client side development</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkID=699322">Develop on different platforms</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkID=699323">Read more on the documentation site</a></li>  
            </ul>  
        </div>  
        <div class="col-md-3">  
            <h2>Run &amp; Deploy</h2>  
            <ul>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkID=517851">Run your app</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkID=517853">Run tools such as EF migrations and more</a></li>  
                <li><a href="https://go.microsoft.com/fwlink/?LinkID=398609">Publish to Microsoft Azure App Service</a></li>  
            </ul>  
        </div>  
    </div>  
    

    and the original default index.cshtml.cs was modified for users who sign in to the login page as follows:-

    and the original default index.cshtml.cs was modified as follows:-  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Threading.Tasks;  
    using Microsoft.AspNetCore.Mvc;  
    using Microsoft.AspNetCore.Http;  
    using Microsoft.AspNetCore.Mvc.RazorPages;  
      
    namespace Goods_Store.Pages  
    {  
        public class IndexModel : PageModel  
        {  
            public const string UserLogged = "UserLogged";  
            public void OnGet()  
            {  
                var User = HttpContext.Session.GetInt32(UserLogged);  
      
                if(User == null)  
                {  
                    Response.Redirect("/SignIn/Login", false);  
                }  
            }  
        }  
    }  
    

    The code for the Login.cshtml is shown below: -

    @page  
    @model GoodsStore.LoginModel  
      
    @{  
        Layout = null;  
    }  
      
    <!DOCTYPE html>  
      
    <html>  
    <head>  
      
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">  
        @*<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>*@  
        <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>  
      
        <link href="~/css/SignIn/Login.css" rel="stylesheet" />  
      
        <meta name="viewport" content="width=device-width" />  
        <title>Goods Store - LogIn</title>  
    </head>  
    <body>  
      
        <div class="sidenav">  
            <div class="login-main-text">  
                <h2>Goods Store<br> Login Page</h2>  
                <p>Login from here to access.</p>  
            </div>  
        </div>  
        <div class="main">  
            <div class="col-md-6 col-sm-12">  
                <div class="login-form">  
                    <form method="post">  
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
                        <div class="form-group">  
                            <label asp-for="SignIn.Email" class="control-label"></label>  
                            <input asp-for="SignIn.Email" class="form-control" />  
                            <span asp-validation-for="SignIn.Email" class="text-danger"></span>  
                        </div>  
                        <div class="form-group">  
                            <label asp-for="SignIn.Password" class="control-label"></label>  
                            <input asp-for="SignIn.Password" class="form-control" type="password" />  
                            <span asp-validation-for="SignIn.Password" class="text-danger"></span>  
                        </div>  
                        <button type="submit" class="btn btn-black">Login!</button>  
                        <button type="button" class="btn btn-secondary" id="btnSignUp">Go To Sign Up</button>  
                        <h4 class="text-danger">  
                            @ViewData["Mensage"]  
                        </h4>  
                    </form>  
                </div>  
            </div>  
        </div>  
      
        @section Scripts {  
            @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
        }  
    </body>  
      
    </html>  
      
    <script>  
        $(document).ready(function () {  
            $('#btnSignUp').click(function () {            
                urlGet = "@Url.Content("~/SignIn/SignUp")";  
                window.location.href = urlGet;  
            });  
        });  
      
    </script>  
    

    The code for the Login.cshtml.cs is shown below: -

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Threading.Tasks;  
    using Microsoft.AspNetCore.Http;  
    using Microsoft.AspNetCore.Mvc;  
    using Microsoft.AspNetCore.Mvc.RazorPages;  
    using Microsoft.AspNetCore.Mvc.Rendering;  
    using GoodsStore.Models;  
      
    namespace GoodsStore  
    {  
        public class LoginModel : PageModel  
        {  
            private readonly GoodsStore.Models.GoodStorageContext _context;  
            public const string UserLogged = "UserLogged";  
            public LoginModel(GoodsStore.Models.GoodStorageContext context)  
            {  
                _context = context;  
            }  
      
            public IActionResult OnGet()  
            {  
                return Page();  
            }  
      
            [BindProperty]  
            public SignIn SignIn { get; set; }  
      
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for  
            // more details see https://aka.ms/RazorPagesCRUD.  
            public async Task<IActionResult> OnPostAsync()  
            {  
                if (!ModelState.IsValid)  
                {  
                    return Page();  
                }  
      
                var user = _context.SignIn.FirstOrDefault(u => u.Email == SignIn.Email.Trim() && u.Password == SignIn.Password.Trim());  
                await _context.SaveChangesAsync();  
      
                if (user != null)  
                {  
                    HttpContext.Session.SetInt32(UserLogged, user.ID);  
                    return RedirectToPage("/Welcome/Index");  
                }  
                else  
                {  
                    ViewData["Message"] = "Email or Password no match";  
                }  
      
                return Page();  
            }  
        }  
    }  
    

    When I build a solution output, the Login Form appears, and once the user logs in the Services webpage, I see the Home weblink and About Us weblink on the Dashboard. If I click on the Home weblink, the original default Index webpage (i.e. original default Microsoft Home page with the carousel window and Learn about Asp.Net and Learn about Microsoft Azure cloud information etc.) appears. If I click on “About Us” webpage, it correctly loads the “About Us” webpage which contains information about the business.

    However, I would like the Home page, About Us, Login navigation men links to appear on the default landing webpage of the website instead of appearing inside the Login Portal.

    Thank you in advance.

    0 comments No comments