14 Mar 2024
Advanced
In ASP.NET Core WebAPI, builder.Build() and app.Run() serve different purposes in the application startup process.
-
builder.Build():buildertypically refers to an instance ofWebHostBuilderorHostBuilder, which is used to configure and build the web host for the application.Build()method creates an instance ofIWebHostorIHost, which represents the web host for the application.- It initializes and prepares the application to start serving requests.
- It's usually called once in the
Program.csfile during application startup.
-
app.Run():apptypically refers to an instance ofIApplicationBuilder, which is used to configure the HTTP request processing pipeline.Run()method configures a request pipeline to handle HTTP requests. It's the endpoint where the request processing pipeline starts.- It's used to specify a terminal middleware that handles requests and generates responses.
Run()method should be the last middleware configured in the pipeline.
Here's a simple example to illustrate these concepts:
// Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace MyWebAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run(); // Builds the web host and starts the application
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>(); // Configures the startup class for the application
});
}
}
// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyWebAPI
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Configure services such as dependency injection
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
In this example:
CreateHostBuilder(args).Build().Run()inProgram.csbuilds the web host and starts the application.ConfigureServices()method inStartup.csis used to configure services for dependency injection.Configure()method inStartup.csis used to configure the request pipeline.app.UseRouting()sets up routing, andapp.UseEndpoints()configures the endpoint to handle requests.endpoints.MapGet()inConfigure()method defines a simple route that responds with "Hello World!" for the root URL ("/").
So, builder.Build() creates the host, and app.Run() starts the application's HTTP request processing pipeline.