Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why again simply empty app.Run() does we need?

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.
like image 754
Hax Avatar asked Jan 20 '26 20:01

Hax


1 Answers

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.

like image 88
StriplingWarrior Avatar answered Jan 23 '26 10:01

StriplingWarrior