3
votes

I created a default Blazor project and wanted to have a Web API part in the same project for prototyping purposes.

So I put all the controllers and related in an Api subfolder and the Blazor stuff in a Blazor subfolder.

The structure of the project:

- Api
  - Controllers
    - AController.cs
- Blazor
  - Pages
    - _Host.cshtml
    - Counter.razor
    - Error.razor
    - FetchData.razor
    - Index.razor
  - Data
    - WeatherForecast.cs
    - WeatherForecastService.cs
  - Shared
    - MainLayout.razor
    - NavMenu.razor
  - _Imports.razor
  - App.razor
- appsettings.json
- appsettings.Development.json
- Program.cs
- Startup.cs

Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "An API", 
                Version = "Version Yoohoo"
            });

            var xmlFileName = Assembly.GetExecutingAssembly().GetName().Name + ".xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFileName);

            options.IncludeXmlComments(xmlPath);
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

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

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });

        app.UseSwagger();
        app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"));
    }
}

But now when starting the app, I am having the exception below:

An unhandled exception occurred while processing the request. InvalidOperationException: Cannot find the fallback endpoint specified by route values: { page: /_Host, area: }. Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DynamicPageEndpointMatcherPolicy.ApplyAsync(HttpContext httpContext, CandidateSet candidates)

How can I fix that?

1

1 Answers

4
votes

You also need to change the default root directory for Razor Pages, try to add below code in startup ConfigureServices

services.Configure<RazorPagesOptions>(options => options.RootDirectory = "/Blazor/Pages");