WebApplicationBuilder (web applications)

Template Overview

Template Minimal API

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

// or without a builder 

var app = WebApplication.Create(args);

app.MapGet("/", () => "Hello World!");

app.Run();

Template Controller-Based API

Project.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

Controller.cs

[ApiController]
[Route("[controller]")]
public class AutomationController : ControllerBase
{
    private readonly ILogger<AutomationController> _logger;

    public AutomationController(ILogger<AutomationController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public int Get()
    {
        return 1;
    }
}

Ports

Ports are normally specified in the Properties/launchSettings.json, however you can also specify it manually like so:

app.Urls.Add("http://localhost:3000");
app.Urls.Add("http://localhost:4000");

You can also set ports via the ASPNETCORE_URLSย env var.

ASPNETCORE_URLS=http://localhost:3000

// or specify multiple ports

ASPNETCORE_URLS=http://localhost:3000;https://localhost:5000

Specify HTTPS with custom Certificate

appsettings.json

{
  "Kestrel": {
    "Certificates": {
      "Default": {
        "Path": "cert.pem",
        "KeyPath": "key.pem"
      }
   }
}

Web Application Builder Setup

Options

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();