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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Retry later