In order to see how to create a .NET Core Web Application with Razor Pages and retrieve data from SQL Server using Entity Framework, you can visit my previous article.
Below are the software/concepts used in this document.
- Visual Studio 2019
- Razor Pages
- .Net Core 2.0
- Net Core Web Application
- C# Language
Open your project in Visual Studio 2019
In my case, I am opening the earlier-created project where Razor pages are present. Once you browse this web application in the browser, the Index.cshtml page is opened by default.
Make Custom Razor Page as default home/landing page
In my example, I want a custom Razor page named “Index.cshtml” under “Customers” folder to be my home/landing page.
You might have seen that Razor Pages are designed to open the Index page by default within the current folder. Example:
- If we browse for http://localhost:44381/customers/index, it would by default open http://localhost:44381/customers/index.cshtml
- If we browse for http://localhost:44381/customers/, it would by default open http://localhost:44381/customers/index.cshtml
- But if we browse http://localhost:44381/, it would by default open http://localhost:44381/index.cshtml, which we have to change
- Open the Startup.cs file and update the “ConfigureServices” method as below.
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options =>
- {
-
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
- services.AddMvc().AddRazorPagesOptions(options=> {
- options.Conventions.AddPageRoute("/Customers/Index", "");
- }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
-
-
- }
- }
Here, we are using the AddRazorPagesOptions() method which helps in setting things like route conventions and the root directory for pages. I am using AddPageRoute() method which has the first parameter taking the path to the page which I want to make a new home/landing page. The second identifies the route that should map to the page. In my case, since I wanted the default page for the entire app to be the /customers/Index.cshtml page, I am passing in an empty string.
- Delete the old “Index.cshtml” file, as we would not use it anymore. If you don’t delete, the system may throw an error.
- Test the files by right-clicking on the Index file and opening it with browser. The new homepage will open by default.
That is it. I hope you have learned something new from this article and will utilize this in your work.