I'm struggling at embedding kestrel inside a WinForm application using .NET 6. I've found many examples about that but with older .NET version and as I know the migration from .NET 5 to 6 has a lot of breaking changes. The Microsoft documentation, in my opinion is more confusing than helping, expecially from my previous Java experience. What I need is a simple webserver embedded in winform application configured to answer to a couple of rest endpoints. That is.
Used this https://jason-ge.medium.com/host-kestrel-web-server-in-net-6-windows-form-application-8b0fd70b4288 as starting point but it's lacking a downloadble example and many classes have no reference and thus, it won't compile.
Thank you very much.
Edit: Some code...I've made it to run but I don't know if it's good:
[STAThread]
static void Main()
{
Task.Run(() => StartWebServer());
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ApplicationConfiguration.Initialize();
Form = new MainForm();
Application.Run(Form);
}
private static void StartWebServer()
{
var builder = WebApplication.CreateBuilder();
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.WebHost.UseKestrel().ConfigureKestrel(serverOptions =>
{
serverOptions.ListenLocalhost(80);
});
var app = builder.Build();
app.MapGet("/{id}", (int id, [FromHeader(Name = "X-SIGN-DOCUMENT")] string document) =>
{
return "Hello " + id + " doc = [" + document + "]";
}
);
app.Run();
}
I've also the Startup class but I don't know if it's used. It is good? Is there a better way?
Thank you!