MVC Windows Service
Without IIS or Nginx, we can publish our dotnet web application as a windows or linux service. Although it can be done in previous versions, the example I will give is made with dotnet6. I will use an MVC example for speed.
Necessary nuget libraries:
For Windows -> Microsoft.Extensions.Hosting.WindowsServices
For Linux -> Microsoft.Extensions.Hosting.Systemd
var webApplicationOptions = new WebApplicationOptions() { ContentRootPath = AppContext.BaseDirectory, Args = args, ApplicationName = System.Diagnostics.Process.GetCurrentProcess().ProcessName };
var builder = WebApplication.CreateBuilder(webApplicationOptions);
builder.Services.AddControllersWithViews();
//builder.Host.UseWindowsService(); //windows için
//builder.Host.UseSystemd(); //linux için
var app = builder.Build();
if (!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseStaticFiles();
app.UseCors(c=> c.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.Run();
To run as a Windows service;
sc.exe create "HttpWorker" binpath="C:\...\Release\net6.0\publish\HttpWorker.exe"
sc.exe stop "HttpWorker"
sc.exe delete "HttpWorker"
I am not giving an example of Linux service setup, it may vary depending on the Linux operating system.