Home > Software design >  Why again simply empty app.Run() does we need?
Why again simply empty app.Run() does we need?

Time:09-08

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.

CodePudding user response:

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.

CodePudding user response:

All the code before app.Run() is merely setting up your app. You need to call app.Run() to run the app. That call basically never ends, which is why the code after it isn't called.

So, the only code you should have after app.Run() would be things like static helper functions. Normally, app.Run() would be the last thing in the file.

If that isn't clear, let me know what I need to explain.

  • Related