Home > database >  Self-host Asp.net Web API in .Net 6.0 project
Self-host Asp.net Web API in .Net 6.0 project

Time:12-23

I would like to add a simple Web API to an already existing .net backend process. The project is already updated to .net 6.0 and I would like to stay at 6.0. I can't figure out how to add the correct references to my project to be able to self-host a web api within my process.

The goal is to have a single executable (mostly) to copy to a small embedded linux system within which the backend and a webserver (serving the static files and acting as a backend for the served frontend).

The 'old' tutorials (.net 5.0) suggest to add a reference to the nuget package "Microsoft.AspNet.WebApi.OwinSelfHost" but it seems as if that package didn't make the transistion to 6.0. (I get errors on installing it complaining about the target framework being unsupported)

CodePudding user response:

You can use Microsoft.AspNetCore.Owin in .Net6.

enter image description here

Test Result

enter image description here


Program.cs

using Microsoft.AspNetCore.Hosting;

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

            host.Run();
        }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

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

Controller file

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace selfhost.Controller
{
    public class SayHiController : ControllerBase
    {
        [Route("sayhi/{name}")]
        public IActionResult Get(string name)
        {
            return Ok($"Hello {name}");
        }
        [Route("getguid")]
        public IActionResult GetGuid(string name)
        {
            return Ok($"{Guid.NewGuid().ToString()}");
        }
    }
}
  • Related