Wanting to add some functionality to query your application for a status, or start an action? maybe you want to write a whole web ui/control panel separately from the application. Well, let’s take a look at a very basic approach of how we can do this.
First of all, your project needs to be .NET Core (6/7/8) and you can start by referencing Microsoft.AspNetCore.App
and Microsoft.Extensions.Hosting
these can be found by right clicking your project in Visual Studio and choosing “Manage NuGet Packages for Solution”, then click Install on both of these packages.
Add the following to your project namespace in the MainForm class:
private IHost _webHost;
We’ll want to start up the webserver as soon as the form is loaded, so we’ll add the following to your form initialization:
public Form1()
{
InitializeComponent();
SetupWebserver();
}
Now for simplicity we’ll do all the logic inside the SetupWebserver
method we’re about to create:
private void SetupWebserver()
{
_webHost = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel()
.UseUrls("http://localhost:5000") // Set the host and port here
.ConfigureServices(services =>
{
services.AddRouting();
});
webBuilder.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/api/status", async context =>
{
var status = new { Status = "Application Running", State = "Idle" };
await context.Response.WriteAsJsonAsync(status);
});
});
});
})
.Build();
_webHost.Start();
}
It’s literally that simple. Just duplicate the endpoints.MapGet
block to add more endpoints to your application. In the example above we return a “status” which is JSON encoded back to the client, but this could also call other methods and return the output of something (for example, starting/stopping actions)
Don’t forget to stop and dispose of the webhost object when we’re done with it, create an event for the mainform of FormClosing and dispose and stop it there, like so:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
_webHost.StopAsync().Wait();
_webHost.Dispose();
}
This is an extremely quick and fast example of how you can make a simple server to provide an “API” or web controller for your application. Of course it can be built upon and improved, but it’s a good start.