I've got app in .net core 5.
And this is the code in Startup.cs
'''''
public static IHostBuilder CreateHostBuilder(string[] args) =>
//Host.CreateDefaultBuilder(args)
// .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder
.UseStartup<Startup>()
.UseKestrel(o =>
{
o.Listen(IPAddress.Any, 443, opt =>
{
opt.UseHttps("pathfto.pfx", "passwordtocert");
});
});
});
I would like to take upgrade it to .net core 6
I thought that it would be like this
var builder = WebApplication.CreateBuilder(args);
builder.Host
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseKestrel(o =>
{
o.Listen(IPAddress.Any, 443, opt => { opt.UseHttps("pathto.pfx", "passwordtocert"); });
});
});
But it doesn't work when I try compile it.
Thank you in advance for any solutions.
Try to use builder.WebHost
builder.WebHost.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Any, int.Parse(builder.Configuration.GetSection("SSL")["port"]), listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
if (builder.Configuration.GetSection("SSL")["sertificateName"].Trim() != "")
listenOptions.UseHttps(Path.Combine(AppContext.BaseDirectory, "cfg", builder.Configuration.GetSection("SSL")["sertificateName"]), builder.Configuration.GetSection("SSL")["password"]);
});
});
More details you find on https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0
Your problem is your trying builder.Host instead of builder.WebHost. I think this would be the equivalent.
Program.cs
builder.WebHost.ConfigureKestrel(opt => {
opt.ListenAnyIP(443, listOpt =>
{
listOpt.UseHttps(#"pathto.pfx", "passwordtocert");
});
});
var app = builder.Build();
Related
I don't want to use CreateDefaultBuilder and ConfigureWebHostDefaults in Program.cs file. Both of these functions make certain assumptions, that I am not comfortable with, also I don't want to rely on ASP.net defaults. I want to setup builder myself but don't know how to do that
I want to replace following code with my own builder
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.Sources.Clear();
...
})
.ConfigureWebHostDefaults(webBuilder =>
{
...
})
.ConfigureServices((context, services) =>
services.Configure<...>(
context.Configuration.GetSection("...")))
.Build();
You can create an instance of HostBuilder directly:
var host = new HostBuilder()
.Build();
HostBuilder has a number of useful methods, such as ConfigureServices, ConfigureAppConfiguration, etc:
var host = new HostBuilder()
.ConfigureAppConfiguration(builder =>
{
// ...
})
.ConfigureServices((context, services) =>
{
// ...
})
.Build();
To configure the WebHost, without the defaults, use ConfigureWebHost:
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
})
.Build();
How can I setup listening multiple ports? On first port I want to have default app with https, on another I want to use HTTPS and require SSL based authentication with client certificates. How to do it? This is my current Startup.cs code:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(kestrelOptions =>
{
kestrelOptions.ConfigureHttpsDefaults(httpOptions =>
{
httpOptions.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
});
});
var services = builder.Services;
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cfg =>
{
cfg.ReturnUrlParameter = "returnUrl";
cfg.LoginPath = "/account/login";
cfg.LogoutPath = "/account/logout";
})
.AddCertificate(CertificateAuthenticationDefaults.AuthenticationScheme, cfg =>
{
cfg.AllowedCertificateTypes = CertificateTypes.All;
cfg.RevocationMode = X509RevocationMode.Online;
});
services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
My goal is to use Certificate authentication on some endpoints (and don't display certificate request e.g. for web explorer users) and not use delayed certificates.
I did it with kestrelOptions.ListenLocalhost:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(kestrelOptions =>
{
kestrelOptions.ListenLocalhost(8080, cfg =>
{
cfg.UseHttps(httpOptions =>
{
httpOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
});
kestrelOptions.ListenLocalhost(8081, cfg =>
{
cfg.UseHttps(httpOptions =>
{
httpOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate;
});
});
});
Now one port is for mTLS (8080) and another don't require certificate! Works really nice.
I am creating a Worker application using Net 6 and I have in Program.cs:
IHostBuilder builder = Host.CreateDefaultBuilder(args);
builder.ConfigureHostConfiguration(x => {
x.AddJsonFile("settings.json", false, true);
x.AddJsonFile($"settings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false, true);
x.AddEnvironmentVariables();
});
builder.UseSerilog(new LoggerBuilder(
new LoggerOptions {
ConnectionString = builder.Configuration.Get<Options>().ConnectionString
},
).CreateLogger());
In LoggerOptions I need to get Options and the ConnectionString from it.
I tried the following because that is what I do when using WebApplicationBuilder:
builder.Configuration.Get<Options>().ConnectionString
But this does not compile as it seems IHostBuilder does not have a Configuration property.
How can I do this?
Simple example:
var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.UseSerilog((hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
});
hostBuilder.ConfigureServices((hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
}
You can access it by using the configure services overload that accepts the HostBuilderContext. I don't typically use the LoggerBuilder:
IHost host = Host.CreateDefaultBuilder(args)
.UseSerilog((context, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(context.Configuration);
})
.Build();
await host.RunAsync();
Trying to setup Azure App Configuration with Azure Key Vault in Program.cs and getting following error:
'IConfigurationBuilder' does not contain a definition for
'AddAzureAppConfiguration'
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options.Connect(settings["ConnectionStrings:AppConfig"])
.ConfigureKeyVault(kv =>
{
kv.SetCredential(new DefaultAzureCredential());
});
});
})
.UseStartup<Startup>());
adding following package fixed it:
dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
Or even better:
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration
Clear and simple Microsoft Documentation for the App Config integration.
I've tried various attempts at getting logging to show in Azure, but nothing is working. My latest attempt was this:
https://ardalis.com/configuring-logging-in-azure-app-services/
I added this to my project:
https://www.nuget.org/packages/Microsoft.Extensions.Logging.AzureAppServices
In Programs.cs, I did this:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
logging.AddAzureWebAppDiagnostics();
});
});
And I have this line in an API controller method that gets called:
_logger.LogWarning("Test warning logging.");
I also tried logging this way:
Trace.TraceWarning("Test warning logging (trace).");
My Azure App Service Logs settings look like this:
Yet, when I go to log stream, there are never any messages:
I'm at a lost as to what to try next.
In your Programs.cs, the ConfigureLogging(logging=>{xxx}) should not be placed within ConfigureWebHostDefaults. You should use the following code in your Programs.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging=> {
logging.ClearProviders();
logging.AddConsole();
logging.AddAzureWebAppDiagnostics();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Then I'm using this line of code to send logs:
_logger.LogInformation("this is an information from index page...");
Then in azure portal, the message is there: