Self hosting HTTP(s) endpoints in .net core app without using asp.net?

As mentioned by @ADyson, OWIN is the way to go. You can easily self-host a HTTP endpoint in your existing application. Here is a sample to self-host it in a .Net Core 3.1 console application. It exposes a simple endpoint listening on port 5000 for GET requests using a controller. All you need is to install the Microsoft.AspNetCore.Owin Nuget package.

The code files structure is as follows:

.
├── Program.cs
├── Startup.cs
├── Controllers
    ├── SayHi.cs

Program.cs

using Microsoft.AspNetCore.Hosting;

namespace WebApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls("http://*:5000")
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

Startup.cs

using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace WebApp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

SayHi.cs

using Microsoft.AspNetCore.Mvc;

namespace WebApp.Controllers
{
    public class SayHi : ControllerBase
    {
        [Route("sayhi/{name}")]
        public IActionResult Get(string name)
        {
            return Ok($"Hello {name}");
        }
    }
}

Then a simple dotnet WebApp.dll would start the app and web server. As you can see, the sample uses Kestrel. The default web server. You can check Microsoft's related documentation.

For more configuration and routing options you can check Microsoft's documentation.


One option is to use EmbeddIo

https://unosquare.github.io/embedio/

I find the documentation is not always the best, especially as they recently upgrade and many samples etc. are not valid. But you can get there!

You can self host a REST API like this:

 WebServer ws = new WebServer(o => o
        .WithUrlPrefix(url)
        .WithMode(HttpListenerMode.EmbedIO))
        .WithWebApi("/api", m => m
        .WithController<ApiController>());

this.Cts = new CancellationTokenSource();
var task = Webserver.RunAsync(Cts.Token);

Then define your API Controller like this.

class ApiController : WebApiController
 {
        public ApiController() : base()
        {

        }

        [Route(HttpVerbs.Get, "/hello")]
        public async Task HelloWorld()
        {
            string ret;
            try
            {
                ret = "Hello from webserver @ " + DateTime.Now.ToLongTimeString();
            }
            catch (Exception ex)
            {
                //
            }
            await HttpContext.SendDataAsync(ret);

        }
}

Project files generated with dotnet new web in version 2.1 automatically added references to "Microsoft.AspNetCore.App" and "Microsoft.AspNetCore.Razor.Design" which, when referenced by a .net core project and executed ended up with an System.IO.FileNotFoundException stating it "Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core'".

Creating a project with dotnet new web in version 3.1 does not reference these, thus the project can be referenced and executed from a .net core application.

-> Using asp.net core is a viable solution for me (again)!