10

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 ?

ceds
  • 2,097
  • 5
  • 32
  • 50

1 Answers1

10

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:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • This looks like the ASP.NET Web API template. I have an existing .NET 6 library. How do I make this work without using the ASP.NET template ? I just want to call a function that starts the Web API from my existing library. DO I just add ASPNetCore as a reference and use the code as is ? – ceds Jul 22 '22 at 06:14
  • @ceds you can add reference to the [ASP.NET Core shared framework](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/target-aspnetcore?view=aspnetcore-6.0&tabs=visual-studio#use-the-aspnet-core-shared-framework) to your library. Though I would recommend creating another one like `MyLyb.Web` so users which don't need web server can skip the dependency. – Guru Stron Jul 22 '22 at 06:17
  • I installed Microsoft.AspNetCore as a package. However, the WebApplication method is still missing. Not sure if I'm doing this right. – ceds Jul 22 '22 at 06:31
  • 1
    @ceds please read the link in my previous comment. You should not install that nuget package cause it is for pre 3.0 versions of ASP.NET Core. – Guru Stron Jul 22 '22 at 06:33
  • Ok sorry for that. I see you need to edit the project config file. That seemed to have worked for me. Need to do more testing with this. Thanks for your patience and assistance. This .NET environment is really confusing with all the different changes and compatibility issues from one to the next – ceds Jul 22 '22 at 06:41
  • I've accepted your answer but I think it might help others to list this step-by-step – ceds Jul 22 '22 at 07:03
  • 1
    @ceds were you able to make this work with controllers also? It works for me with minimal API (I get a response), but I am unable to make this work by using ApiControllers and app.MapControllers(), I get 404 from all my controller endpoints. – Mr Squidr Nov 29 '22 at 15:51