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

Adding a default Razor page/index to a .Net Core API project


I'd like to add a default page/index page that is Razor (cshtml) to my .NET Core 6 project. I've created the wwwroot directory inside my project, and added a Razor page named index.cshtml inside of it. In it, I've added some HTML and added @page "/" to signify that it should be the root.

Because it is an API project, in my launchSettings.json file, I've commented out the launchurl so that it is no longer pointing to swagger:

enter image description here

In my Program.cs, I've tried both including and excluding the following code (I think it should be excluded since cshtml is not a static file):

app.UseStaticFiles( new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine( Directory.GetCurrentDirectory(), @"wwwroot" ) )
} );

However, the end result is the same - when I run my API locally, my browser opens to a blank page. Is there something I've missed? I tried adding a static page (index.html) and it did work, but I need the functionality of a Razor page. What am I missing?


Solution

  • I'd like to add a default page/index page that is Razor (cshtml) to my .NET Core 6 project.

    I have a suggestion like below, hope it can help.

    1.In Program.cs, add below code:

    builder.Services.AddRazorPages();
    ...
    app.MapRazorPages();
    

    2.Then add a Pages folder like:

    enter image description here

    3.And in the Index.cshtml add @page "/"

    4.And commented out below code in your aunchSettings.json file as yours:

    "launchUrl": "swagger",
    

    5.result: enter image description here