I want to implement both
- a ASP.NET Core Blazor Server
- and a ASP.NET Core Web API (the server part, not the consumer/client)
in the same process using .NET 6 and run it self-hosted with Kestrel, i.e. without IIS.
I assume the key is the service and middleware pipeline configuration as found in the according Program.cs templates. Here are the two templates that VS 2022 (17.1.5) creates for me:
For the Blazor Server App:
using BlazorApp1.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
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.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
For the ASP.NET Core Web API App:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
So the question is how can I combine these two into one?
I want to:
- Have my program listening to a single port
- Host the Blazor web pages
- But process the API when the URL myhost:port/api/.. is being accessed (without interfering with the Blazor part)
- Have the SwaggerUI, preferably under myhost:port/api/swagger/index.html (again without interfering with the Blazor part)
- Use the same security mechanism based on a client certificate for both