Events
Power BI DataViz World Championships
Feb 14, 4 PM - Mar 31, 4 PM
With 4 chances to enter, you could win a conference package and make it to the LIVE Grand Finale in Las Vegas
Learn moreThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.
Warning
This version of ASP.NET Core is no longer supported. For more information, see the .NET and .NET Core Support Policy. For the current release, see the .NET 9 version of this article.
Important
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 9 version of this article.
The following code is generated by an ASP.NET Core template:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
The preceding code can be created via dotnet new web
on the command line or selecting the Empty Web template in Visual Studio.
The following code creates a WebApplication (app
) without explicitly creating a WebApplicationBuilder:
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
WebApplication.Create
initializes a new instance of the WebApplication class with preconfigured defaults.
WebApplication
automatically adds the following middleware in Minimal API applications
depending on certain conditions:
UseDeveloperExceptionPage
is added first when the HostingEnvironment
is "Development"
.UseRouting
is added second if user code didn't already call UseRouting
and if there are endpoints configured, for example app.MapGet
.UseEndpoints
is added at the end of the middleware pipeline if any endpoints are configured.UseAuthentication
is added immediately after UseRouting
if user code didn't already call UseAuthentication
and if IAuthenticationSchemeProvider
can be detected in the service provider. IAuthenticationSchemeProvider
is added by default when using AddAuthentication
, and services are detected using IServiceProviderIsService
.UseAuthorization
is added next if user code didn't already call UseAuthorization
and if IAuthorizationHandlerProvider
can be detected in the service provider. IAuthorizationHandlerProvider
is added by default when using AddAuthorization
, and services are detected using IServiceProviderIsService
.UseRouting
and UseEndpoints
.The following code is effectively what the automatic middleware being added to the app produces:
if (isDevelopment)
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
if (isAuthenticationConfigured)
{
app.UseAuthentication();
}
if (isAuthorizationConfigured)
{
app.UseAuthorization();
}
// user middleware/endpoints
app.CustomMiddleware(...);
app.MapGet("/", () => "hello world");
// end user middleware/endpoints
app.UseEndpoints(e => {});
In some cases, the default middleware configuration isn't correct for the app and requires modification. For example, UseCors should be called before UseAuthentication and UseAuthorization. The app needs to call UseAuthentication
and UseAuthorization
if UseCors
is called:
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
If middleware should be run before route matching occurs, UseRouting should be called and the middleware should be placed before the call to UseRouting
. UseEndpoints isn't required in this case as it is automatically added as described previously:
app.Use((context, next) =>
{
return next(context);
});
app.UseRouting();
// other middleware and endpoints
When adding a terminal middleware:
UseEndpoints
.UseRouting
and UseEndpoints
so that the terminal middleware can be placed at the correct location.app.UseRouting();
app.MapGet("/", () => "hello world");
app.UseEndpoints(e => {});
app.Run(context =>
{
context.Response.StatusCode = 404;
return Task.CompletedTask;
});
Terminal middleware is middleware that runs if no endpoint handles the request.
When a web app is created with Visual Studio or dotnet new
, a Properties/launchSettings.json
file is created that specifies the ports the app responds to. In the port setting samples that follow, running the app from Visual Studio returns an error dialog Unable to connect to web server 'AppName'
. Visual Studio returns an error because it's expecting the port specified in Properties/launchSettings.json
, but the app is using the port specified by app.Run("http://localhost:3000")
. Run the following port changing samples from the command line.
The following sections set the port the app responds to.
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run("http://localhost:3000");
In the preceding code, the app responds to port 3000
.
In the following code, the app responds to port 3000
and 4000
.
var app = WebApplication.Create(args);
app.Urls.Add("http://localhost:3000");
app.Urls.Add("http://localhost:4000");
app.MapGet("/", () => "Hello World");
app.Run();
The following command makes the app respond to port 7777
:
dotnet run --urls="https://localhost:7777"
If the Kestrel endpoint is also configured in the appsettings.json
file, the appsettings.json
file specified URL is used. For more information, see Kestrel endpoint configuration
The following code reads the port from the environment:
var app = WebApplication.Create(args);
var port = Environment.GetEnvironmentVariable("PORT") ?? "3000";
app.MapGet("/", () => "Hello World");
app.Run($"http://localhost:{port}");
The preferred way to set the port from the environment is to use the ASPNETCORE_URLS
environment variable, which is shown in the following section.
The ASPNETCORE_URLS
environment variable is available to set the port:
ASPNETCORE_URLS=http://localhost:3000
ASPNETCORE_URLS
supports multiple URLs:
ASPNETCORE_URLS=http://localhost:3000;https://localhost:5000
For more information using the environment, see Use multiple environments in ASP.NET Core
The following samples demonstrate listening on all interfaces
var app = WebApplication.Create(args);
app.Urls.Add("http://*:3000");
app.MapGet("/", () => "Hello World");
app.Run();
var app = WebApplication.Create(args);
app.Urls.Add("http://+:3000");
app.MapGet("/", () => "Hello World");
app.Run();
var app = WebApplication.Create(args);
app.Urls.Add("http://0.0.0.0:3000");
app.MapGet("/", () => "Hello World");
app.Run();
The preceding samples can use ASPNETCORE_URLS
ASPNETCORE_URLS=http://*:3000;https://+:5000;http://0.0.0.0:5005
var app = WebApplication.Create(args);
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
For more information on the development certificate, see Trust the ASP.NET Core HTTPS development certificate on Windows and macOS.
The following sections show how to specify the custom certificate using the appsettings.json
file and via configuration.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"Certificates": {
"Default": {
"Path": "cert.pem",
"KeyPath": "key.pem"
}
}
}
}
var builder = WebApplication.CreateBuilder(args);
// Configure the cert and the key
builder.Configuration["Kestrel:Certificates:Default:Path"] = "cert.pem";
builder.Configuration["Kestrel:Certificates:Default:KeyPath"] = "key.pem";
var app = builder.Build();
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
using System.Security.Cryptography.X509Certificates;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
options.ConfigureHttpsDefaults(httpsOptions =>
{
var certPath = Path.Combine(builder.Environment.ContentRootPath, "cert.pem");
var keyPath = Path.Combine(builder.Environment.ContentRootPath, "key.pem");
httpsOptions.ServerCertificate = X509Certificate2.CreateFromPemFile(certPath,
keyPath);
});
});
var app = builder.Build();
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
The following code reads from the configuration system:
var app = WebApplication.Create(args);
var message = app.Configuration["HelloKey"] ?? "Config failed!";
app.MapGet("/", () => message);
app.Run();
For more information, see Configuration in ASP.NET Core
The following code writes a message to the log on application startup:
var app = WebApplication.Create(args);
app.Logger.LogInformation("The app started");
app.MapGet("/", () => "Hello World");
app.Run();
For more information, see Logging in .NET Core and ASP.NET Core
The following code shows how to get services from the DI container during application startup:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped<SampleService>();
var app = builder.Build();
app.MapControllers();
using (var scope = app.Services.CreateScope())
{
var sampleService = scope.ServiceProvider.GetRequiredService<SampleService>();
sampleService.DoSomething();
}
app.Run();
For more information, see Dependency injection in ASP.NET Core.
This section contains sample code using WebApplicationBuilder.
The following code sets the content root, application name, and environment:
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ApplicationName = typeof(Program).Assembly.FullName,
ContentRootPath = Directory.GetCurrentDirectory(),
EnvironmentName = Environments.Staging,
WebRootPath = "customwwwroot"
});
Console.WriteLine($"Application Name: {builder.Environment.ApplicationName}");
Console.WriteLine($"Environment Name: {builder.Environment.EnvironmentName}");
Console.WriteLine($"ContentRoot Path: {builder.Environment.ContentRootPath}");
Console.WriteLine($"WebRootPath: {builder.Environment.WebRootPath}");
var app = builder.Build();
WebApplication.CreateBuilder initializes a new instance of the WebApplicationBuilder class with preconfigured defaults.
For more information, see ASP.NET Core fundamentals overview
The following table shows the environment variable and command-line argument used to change the content root, app name, and environment:
feature | Environment variable | Command-line argument |
---|---|---|
Application name | ASPNETCORE_APPLICATIONNAME | --applicationName |
Environment name | ASPNETCORE_ENVIRONMENT | --environment |
Content root | ASPNETCORE_CONTENTROOT | --contentRoot |
The following sample adds the INI configuration provider:
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
For detailed information, see File configuration providers in Configuration in ASP.NET Core.
By default the WebApplicationBuilder reads configuration from multiple sources, including:
appSettings.json
and appSettings.{environment}.json
The following code reads HelloKey
from configuration and displays the value at the /
endpoint. If the configuration value is null, "Hello" is assigned to message
:
var builder = WebApplication.CreateBuilder(args);
var message = builder.Configuration["HelloKey"] ?? "Hello";
var app = builder.Build();
app.MapGet("/", () => message);
app.Run();
For a complete list of configuration sources read, see Default configuration in Configuration in ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
// Configure JSON logging to the console.
builder.Logging.AddJsonConsole();
var app = builder.Build();
app.MapGet("/", () => "Hello JSON console!");
app.Run();
var builder = WebApplication.CreateBuilder(args);
// Add the memory cache services.
builder.Services.AddMemoryCache();
// Add a custom scoped service.
builder.Services.AddScoped<ITodoRepository, TodoRepository>();
var app = builder.Build();
Existing extension methods on IHostBuilder can be accessed using the Host property:
var builder = WebApplication.CreateBuilder(args);
// Wait 30 seconds for graceful shutdown.
builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Extension methods on IWebHostBuilder can be accessed using the WebApplicationBuilder.WebHost property.
var builder = WebApplication.CreateBuilder(args);
// Change the HTTP server implemenation to be HTTP.sys based
builder.WebHost.UseHttpSys();
var app = builder.Build();
app.MapGet("/", () => "Hello HTTP.sys");
app.Run();
By default, the web root is relative to the content root in the wwwroot
folder. Web root is where the static files middleware looks for static files. Web root can be changed with WebHostOptions
, the command line, or with the UseWebRoot method:
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
// Look for static files in webroot
WebRootPath = "webroot"
});
var app = builder.Build();
app.Run();
The following example uses Autofac:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// Register services directly with Autofac here. Don't
// call builder.Populate(), that happens in AutofacServiceProviderFactory.
builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new MyApplicationModule()));
var app = builder.Build();
Any existing ASP.NET Core middleware can be configured on the WebApplication
:
var app = WebApplication.Create(args);
// Setup the file server to serve static files.
app.UseFileServer();
app.MapGet("/", () => "Hello World!");
app.Run();
For more information, see ASP.NET Core Middleware
WebApplication.CreateBuilder initializes a new instance of the WebApplicationBuilder class with preconfigured defaults. The developer exception page is enabled in the preconfigured defaults. When the following code is run in the development environment, navigating to /
renders a friendly page that shows the exception.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () =>
{
throw new InvalidOperationException("Oops, the '/' route has thrown an exception.");
});
app.Run();
The following code is generated by an ASP.NET Core template:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
The preceding code can be created via dotnet new web
on the command line or selecting the Empty Web template in Visual Studio.
The following code creates a WebApplication (app
) without explicitly creating a WebApplicationBuilder:
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
WebApplication.Create
initializes a new instance of the WebApplication class with preconfigured defaults.
WebApplication
automatically adds the following middleware in Minimal API applications
depending on certain conditions:
UseDeveloperExceptionPage
is added first when the HostingEnvironment
is "Development"
.UseRouting
is added second if user code didn't already call UseRouting
and if there are endpoints configured, for example app.MapGet
.UseEndpoints
is added at the end of the middleware pipeline if any endpoints are configured.UseAuthentication
is added immediately after UseRouting
if user code didn't already call UseAuthentication
and if IAuthenticationSchemeProvider
can be detected in the service provider. IAuthenticationSchemeProvider
is added by default when using AddAuthentication
, and services are detected using IServiceProviderIsService
.UseAuthorization
is added next if user code didn't already call UseAuthorization
and if IAuthorizationHandlerProvider
can be detected in the service provider. IAuthorizationHandlerProvider
is added by default when using AddAuthorization
, and services are detected using IServiceProviderIsService
.UseRouting
and UseEndpoints
.The following code is effectively what the automatic middleware being added to the app produces:
if (isDevelopment)
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
if (isAuthenticationConfigured)
{
app.UseAuthentication();
}
if (isAuthorizationConfigured)
{
app.UseAuthorization();
}
// user middleware/endpoints
app.CustomMiddleware(...);
app.MapGet("/", () => "hello world");
// end user middleware/endpoints
app.UseEndpoints(e => {});
In some cases, the default middleware configuration isn't correct for the app and requires modification. For example, UseCors should be called before UseAuthentication and UseAuthorization. The app needs to call UseAuthentication
and UseAuthorization
if UseCors
is called:
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
If middleware should be run before route matching occurs, UseRouting should be called and the middleware should be placed before the call to UseRouting
. UseEndpoints isn't required in this case as it is automatically added as described previously:
app.Use((context, next) =>
{
return next(context);
});
app.UseRouting();
// other middleware and endpoints
When adding a terminal middleware:
UseEndpoints
.UseRouting
and UseEndpoints
so that the terminal middleware can be placed at the correct location.app.UseRouting();
app.MapGet("/", () => "hello world");
app.UseEndpoints(e => {});
app.Run(context =>
{
context.Response.StatusCode = 404;
return Task.CompletedTask;
});
Terminal middleware is middleware that runs if no endpoint handles the request.
When a web app is created with Visual Studio or dotnet new
, a Properties/launchSettings.json
file is created that specifies the ports the app responds to. In the port setting samples that follow, running the app from Visual Studio returns an error dialog Unable to connect to web server 'AppName'
. Visual Studio returns an error because it's expecting the port specified in Properties/launchSettings.json
, but the app is using the port specified by app.Run("http://localhost:3000")
. Run the following port changing samples from the command line.
The following sections set the port the app responds to.
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run("http://localhost:3000");
In the preceding code, the app responds to port 3000
.
In the following code, the app responds to port 3000
and 4000
.
var app = WebApplication.Create(args);
app.Urls.Add("http://localhost:3000");
app.Urls.Add("http://localhost:4000");
app.MapGet("/", () => "Hello World");
app.Run();
The following command makes the app respond to port 7777
:
dotnet run --urls="https://localhost:7777"
If the Kestrel endpoint is also configured in the appsettings.json
file, the appsettings.json
file specified URL is used. For more information, see Kestrel endpoint configuration
The following code reads the port from the environment:
var app = WebApplication.Create(args);
var port = Environment.GetEnvironmentVariable("PORT") ?? "3000";
app.MapGet("/", () => "Hello World");
app.Run($"http://localhost:{port}");
The preferred way to set the port from the environment is to use the ASPNETCORE_URLS
environment variable, which is shown in the following section.
The ASPNETCORE_URLS
environment variable is available to set the port:
ASPNETCORE_URLS=http://localhost:3000
ASPNETCORE_URLS
supports multiple URLs:
ASPNETCORE_URLS=http://localhost:3000;https://localhost:5000
The following samples demonstrate listening on all interfaces
var app = WebApplication.Create(args);
app.Urls.Add("http://*:3000");
app.MapGet("/", () => "Hello World");
app.Run();
var app = WebApplication.Create(args);
app.Urls.Add("http://+:3000");
app.MapGet("/", () => "Hello World");
app.Run();
var app = WebApplication.Create(args);
app.Urls.Add("http://0.0.0.0:3000");
app.MapGet("/", () => "Hello World");
app.Run();
The preceding samples can use ASPNETCORE_URLS
ASPNETCORE_URLS=http://*:3000;https://+:5000;http://0.0.0.0:5005
The preceding samples can use ASPNETCORE_HTTPS_PORTS
and ASPNETCORE_HTTP_PORTS
.
ASPNETCORE_HTTP_PORTS=3000;5005
ASPNETCORE_HTTPS_PORTS=5000
For more information, see Configure endpoints for the ASP.NET Core Kestrel web server
var app = WebApplication.Create(args);
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
For more information on the development certificate, see Trust the ASP.NET Core HTTPS development certificate on Windows and macOS.
The following sections show how to specify the custom certificate using the appsettings.json
file and via configuration.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"Certificates": {
"Default": {
"Path": "cert.pem",
"KeyPath": "key.pem"
}
}
}
}
var builder = WebApplication.CreateBuilder(args);
// Configure the cert and the key
builder.Configuration["Kestrel:Certificates:Default:Path"] = "cert.pem";
builder.Configuration["Kestrel:Certificates:Default:KeyPath"] = "key.pem";
var app = builder.Build();
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
using System.Security.Cryptography.X509Certificates;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
options.ConfigureHttpsDefaults(httpsOptions =>
{
var certPath = Path.Combine(builder.Environment.ContentRootPath, "cert.pem");
var keyPath = Path.Combine(builder.Environment.ContentRootPath, "key.pem");
httpsOptions.ServerCertificate = X509Certificate2.CreateFromPemFile(certPath,
keyPath);
});
});
var app = builder.Build();
app.Urls.Add("https://localhost:3000");
app.MapGet("/", () => "Hello World");
app.Run();
var app = WebApplication.Create(args);
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/oops");
}
app.MapGet("/", () => "Hello World");
app.MapGet("/oops", () => "Oops! An error happened.");
app.Run();
For more information using the environment, see Use multiple environments in ASP.NET Core
The following code reads from the configuration system:
var app = WebApplication.Create(args);
var message = app.Configuration["HelloKey"] ?? "Config failed!";
app.MapGet("/", () => message);
app.Run();
For more information, see Configuration in ASP.NET Core
The following code writes a message to the log on application startup:
var app = WebApplication.Create(args);
app.Logger.LogInformation("The app started");
app.MapGet("/", () => "Hello World");
app.Run();
For more information, see Logging in .NET Core and ASP.NET Core
The following code shows how to get services from the DI container during application startup:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped<SampleService>();
var app = builder.Build();
app.MapControllers();
using (var scope = app.Services.CreateScope())
{
var sampleService = scope.ServiceProvider.GetRequiredService<SampleService>();
sampleService.DoSomething();
}
app.Run();
The following code shows how to access keys from the DI container using the [FromKeyedServices]
attribute:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");
var app = builder.Build();
app.MapGet("/big", ([FromKeyedServices("big")] ICache bigCache) => bigCache.Get("date"));
app.MapGet("/small", ([FromKeyedServices("small")] ICache smallCache) => smallCache.Get("date"));
app.Run();
public interface ICache
{
object Get(string key);
}
public class BigCache : ICache
{
public object Get(string key) => $"Resolving {key} from big cache.";
}
public class SmallCache : ICache
{
public object Get(string key) => $"Resolving {key} from small cache.";
}
For more information on DI, see Dependency injection in ASP.NET Core.
This section contains sample code using WebApplicationBuilder.
The following code sets the content root, application name, and environment:
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ApplicationName = typeof(Program).Assembly.FullName,
ContentRootPath = Directory.GetCurrentDirectory(),
EnvironmentName = Environments.Staging,
WebRootPath = "customwwwroot"
});
Console.WriteLine($"Application Name: {builder.Environment.ApplicationName}");
Console.WriteLine($"Environment Name: {builder.Environment.EnvironmentName}");
Console.WriteLine($"ContentRoot Path: {builder.Environment.ContentRootPath}");
Console.WriteLine($"WebRootPath: {builder.Environment.WebRootPath}");
var app = builder.Build();
WebApplication.CreateBuilder initializes a new instance of the WebApplicationBuilder class with preconfigured defaults.
For more information, see ASP.NET Core fundamentals overview
The following table shows the environment variable and command-line argument used to change the content root, app name, and environment:
feature | Environment variable | Command-line argument |
---|---|---|
Application name | ASPNETCORE_APPLICATIONNAME | --applicationName |
Environment name | ASPNETCORE_ENVIRONMENT | --environment |
Content root | ASPNETCORE_CONTENTROOT | --contentRoot |
The following sample adds the INI configuration provider:
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddIniFile("appsettings.ini");
var app = builder.Build();
For detailed information, see File configuration providers in Configuration in ASP.NET Core.
By default the WebApplicationBuilder reads configuration from multiple sources, including:
appSettings.json
and appSettings.{environment}.json
For a complete list of configuration sources read, see Default configuration in Configuration in ASP.NET Core.
The following code reads HelloKey
from configuration and displays the value at the /
endpoint. If the configuration value is null, "Hello" is assigned to message
:
var builder = WebApplication.CreateBuilder(args);
var message = builder.Configuration["HelloKey"] ?? "Hello";
var app = builder.Build();
app.MapGet("/", () => message);
app.Run();
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
Console.WriteLine($"Running in development.");
}
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
var builder = WebApplication.CreateBuilder(args);
// Configure JSON logging to the console.
builder.Logging.AddJsonConsole();
var app = builder.Build();
app.MapGet("/", () => "Hello JSON console!");
app.Run();
var builder = WebApplication.CreateBuilder(args);
// Add the memory cache services.
builder.Services.AddMemoryCache();
// Add a custom scoped service.
builder.Services.AddScoped<ITodoRepository, TodoRepository>();
var app = builder.Build();
Existing extension methods on IHostBuilder can be accessed using the Host property:
var builder = WebApplication.CreateBuilder(args);
// Wait 30 seconds for graceful shutdown.
builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Extension methods on IWebHostBuilder can be accessed using the WebApplicationBuilder.WebHost property.
var builder = WebApplication.CreateBuilder(args);
// Change the HTTP server implemenation to be HTTP.sys based
builder.WebHost.UseHttpSys();
var app = builder.Build();
app.MapGet("/", () => "Hello HTTP.sys");
app.Run();
By default, the web root is relative to the content root in the wwwroot
folder. Web root is where the static files middleware looks for static files. Web root can be changed with WebHostOptions
, the command line, or with the UseWebRoot method:
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
// Look for static files in webroot
WebRootPath = "webroot"
});
var app = builder.Build();
app.Run();
The following example uses Autofac:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// Register services directly with Autofac here. Don't
// call builder.Populate(), that happens in AutofacServiceProviderFactory.
builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new MyApplicationModule()));
var app = builder.Build();
Any existing ASP.NET Core middleware can be configured on the WebApplication
:
var app = WebApplication.Create(args);
// Setup the file server to serve static files.
app.UseFileServer();
app.MapGet("/", () => "Hello World!");
app.Run();
For more information, see ASP.NET Core Middleware
WebApplication.CreateBuilder initializes a new instance of the WebApplicationBuilder class with preconfigured defaults. The developer exception page is enabled in the preconfigured defaults. When the following code is run in the development environment, navigating to /
renders a friendly page that shows the exception.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () =>
{
throw new InvalidOperationException("Oops, the '/' route has thrown an exception.");
});
app.Run();
ASP.NET Core feedback
ASP.NET Core is an open source project. Select a link to provide feedback:
Events
Power BI DataViz World Championships
Feb 14, 4 PM - Mar 31, 4 PM
With 4 chances to enter, you could win a conference package and make it to the LIVE Grand Finale in Las Vegas
Learn moreTraining
Module
Build your first ASP.NET Core web app - Training
Learn how to build your first web app using ASP.NET Core.
Certification
Microsoft Certified: Azure Developer Associate - Certifications
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.
Documentation
Provides an overview of minimal APIs in ASP.NET Core
Create responses in Minimal API applications
Learn how to create responses for minimal APIs in ASP.NET Core.
Learn how the Startup class in ASP.NET Core configures services and the app's request pipeline.