Home > Net >  Self-Hosted Web API in .NET 6
Self-Hosted Web API in .NET 6

Time:07-22

I need to add a very simple Web API to an existing library so that Python can communicate with the application. Simple Request/JSON response. This is more challenging than initially thought. I'm used to NodeJS where a library like Express can do this in a few lines of code.

Obviously the web server needs to be integrated in the library. I cannot be dependent on IIS or any web server.

These kinds of tutorials are all over the web:

https://github.com/jbogard/Docs/blob/master/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api.md

Install: Microsoft.AspNet.WebApi.OwinSelfHost

Main

 static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9000/";

            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                // Create HttpCient and make a request to api/values 
                HttpClient client = new HttpClient();

                var response = client.GetAsync(baseAddress   "api/values").Result;

                Console.WriteLine(response);
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                Console.ReadLine();
            }
        }

Startup

public class Startup
{
    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }
}

Controller

public class ValuesController : ApiController
    {
        // GET api/values 
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5 
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values 
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5 
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5 
        public void Delete(int id)
        {
        }
    }

It seems simple enough, however, it does not work in .NET 6. There seems to be compatibility issues.

I stumbled upon threads like the following ones:

Self Hosting OWIN in .NET Core

NullReferenceException experienced with Owin on Startup .Net Core 2.0 - Settings?

However I'm struggling to find a practical answer onhow to deploy a simple Web API in an existing .NET 6 library. The workaround suggested does not work for me.

Any advice will be appreciated ? Should I rather go for a different library? Is ASP.NET not the right tool to use ?

CodePudding user response:

ASP.NET Core comes with build in and enabled by default web server - Kestrel so there is no need to set up OWIN. The simple setup can look this way (UseKestrel is called internally by WebApplication.CreateBuilder):

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

See also:

  • Related