I'm practicing on a simple web api by C# in which I try to see how pipeline goes on. But if I don't add simply empty app.Run() at the end of file, the program terminates immediately, that is, return 0 without running browser. If I write, it works and prints as expected. Must it be at the end of file even if there is app.Run(blablabla)? As far as I know, app.Run() is the terminator delegate.
Simple Program.cs
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.Use(async (context, next) =>
{
await context.Response.WriteAsync("Before Invoke from 1st app.Use()\n");
await next();
await context.Response.WriteAsync("After Invoke from 1st app.Use()\n");
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Before Invoke from 2nd app.Use()\n");
await next();
await context.Response.WriteAsync("After Invoke from 2nd app.Use()\n");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello from 1st app.Run()\n");
});
// the following will never be executed
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello from 2nd app.Run()\n");
});
// app.Run(); if we comment in, it works. This style doesn't work.
The calls to app.Run(...) where you pass in a delegate are calling this extension method, which only sets up a delegate to be called later when requests come in.
Adds a terminal middleware delegate to the application's request pipeline.
The calls to app.Run() where you provide no argument are calling this method, which actually runs the application.
Runs an application and block the calling thread until host shutdown.
One can certainly question the wisdom of giving these two methods the same name, when they have fundamentally different purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With