Search code examples
c#asp.net-corerazorrazor-pages

Use .razor pages in a web application from a Razor component library


I have a Razor class library that has cshtml pages and i am trying to convert the pages to .razor pages.

On .net 7 I tryed in an empty solution following the doc at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-7.0&tabs=visual-studio

I added the two templates and everythyng works as expected and i can browse the Page1.cshtml added from the template, but if I add, in the same path of Page1.cshtml the razor component Test.razor, I add to it the page directive @page "/test" and try to browse to https://localhost:7054/myfeature/test I get a 404, why?

Is it possible to consume .razor pages from a web application?

This is my services configuration :

    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddControllersWithViews();
    builder.Services.AddRazorPages();

    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        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.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();

    app.MapRazorPages();

    app.Run();

I also tryed to add

    builder.Services.AddServerSideBlazor();

and

    app.MapBlazorHub();

without success


Solution

  • I get a 404, why?

    You should make sure blazor server works well on your side first, all your razor components was rendered on _Host.cshtml by default.this line is required(it maps all routes that don't match your razor page routes to _Host.cshtml,without it you would get 404 err):

    app.MapFallbackToPage("/_Host");
    

    and check this doc if you missed something else required ,such as App.razor

    When it comes to consume ASP.NET Core Razor components from RCL,you could check this doc

    I tried as below on myside:

    enter image description here

    enter image description here

    codes in conponents1 of RCL proj:

    <div class="my-component">
        This component is defined in the <strong>RCL</strong> library.
    </div>
    

    codes in RCLComponent.razor in BalzorServerRCL proj:

    @page "/RCLComponent"
    <RCL.Component1 />
    

    It works:

    enter image description here