DEV Community

artydev
artydev

Posted on

Native AOT minimal API in .NET Core 8

It's now possible to create native web api application.
When compiling the following code, you get a standalone web api, 9M only, great.

using System.Text.Json.Serialization;
using System.Diagnostics;
namespace NativeApi
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var builder = WebApplication.CreateSlimBuilder(args);
      builder.Services.ConfigureHttpJsonOptions(options =>
      {
        options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
      });
      builder.WebHost.ConfigureKestrel((context, serverOptions) =>
      {
        serverOptions.Listen(System.Net.IPAddress.Loopback, 5270);
      });
      var app = builder.Build();
      var lifetime = app.Services.GetRequiredService < IHostApplicationLifetime > ();
      lifetime.ApplicationStopped.Register(() =>
      {
        Console.WriteLine("Terminating application...");
        Process.GetCurrentProcess().Kill();
      });
      var sampleTodos = new Todo[]
      {
        new(1, "Walk the dog"),
        new(2, "Do the dishes", DateOnly.FromDateTime(DateTime.Now)),
        new(3, "Do the laundry", DateOnly.FromDateTime(DateTime.Now.AddDays(1))),
        new(4, "Clean the bathroom"),
        new(5, "Clean the car", DateOnly.FromDateTime(DateTime.Now.AddDays(2)))
      };
      var servicesApi = app.MapGroup("/services");
      var todosApi = app.MapGroup("/todos");
      servicesApi.MapGet("/stop", () =>
      {
        lifetime.StopApplication();
        return "Application is shutting down.";
      });
      todosApi.MapGet("/", () => sampleTodos);
      todosApi.MapGet("/{id}", (int id) => sampleTodos.FirstOrDefault(a => a.Id == id) is
        {}
        todo ? Results.Ok(todo) : Results.NotFound());
      Process.Start(new ProcessStartInfo
      {
        FileName = "cmd",
          WindowStyle = ProcessWindowStyle.Hidden,
          UseShellExecute = false,
          CreateNoWindow = true,
          Arguments = "/C start http://localhost:5270/todos" // Replace with your application's URL
      });
      app.Run();
    }
  }
  public record Todo(int Id, string ? Title, DateOnly ? DueBy = null, bool IsComplete = false);
  [JsonSerializable(typeof(Todo[]))]
  internal partial class AppJsonSerializerContext: JsonSerializerContext
  {}
}
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay