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.
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.
User configured middleware and endpoints are added between 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:
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:
The middleware must be added after UseEndpoints.
The app needs to call UseRouting and UseEndpoints so that the terminal middleware can be placed at the correct location.
Terminal middleware is middleware that runs if no endpoint handles the request.
Working with ports
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.
Multiple ports
In the following code, the app responds to port 3000 and 4000.
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
Read the port from environment
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.
Set the ports via the ASPNETCORE_URLS environment variable
The ASPNETCORE_URLS environment variable is available to set the port:
By default the WebApplicationBuilder reads configuration from multiple sources, including:
appSettings.json and appSettings.{environment}.json
Environment variables
The command line
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);
// Change the HTTP server implemenation to be HTTP.sys based
builder.WebHost.UseHttpSys();
var app = builder.Build();
app.MapGet("/", () => "Hello HTTP.sys");
app.Run();
Change the web root
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();
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();
Add Middleware
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();
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();
WebApplication
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.
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.
User configured middleware and endpoints are added between 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:
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:
The middleware must be added after UseEndpoints.
The app needs to call UseRouting and UseEndpoints so that the terminal middleware can be placed at the correct location.
Terminal middleware is middleware that runs if no endpoint handles the request.
Working with ports
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.
Multiple ports
In the following code, the app responds to port 3000 and 4000.
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
Read the port from environment
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.
Set the ports via the ASPNETCORE_URLS environment variable
The ASPNETCORE_URLS environment variable is available to set the port:
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();
Read the environment
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
Console.WriteLine($"Running in development.");
}
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Add logging providers
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();
Add services
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();
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();
Change the web root
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();
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();
Add Middleware
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();
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();
Samarbeta med oss på GitHub
Källan för det här innehållet finns på GitHub, där du även kan skapa och granska ärenden och pull-begäranden. Se vår deltagarguide för mer information.
Feedback om ASP.NET Core
ASP.NET Core är ett öppen källkod projekt. Välj en länk för att ge feedback:
Skapa lösningar från slutpunkt till slutpunkt i Microsoft Azure för att skapa Azure Functions, implementera och hantera webbappar, utveckla lösningar som använder Azure Storage med mera.