Controllers

Live on this server

Uses controllers to implement a web service, similar to ASP.NET Core MVC.

ControllerSample.cs74 lines
using GenHTTP.Api.Content;
using GenHTTP.Api.Protocol;

using GenHTTP.Modules.Controllers;
using GenHTTP.Modules.Layouting;
using GenHTTP.Modules.Reflection;

public static class ControllerSample
{

    public static IHandlerBuilder Create()
    {
        /*
         *
         * Shows how to declare and register a controller that will be invoked
         * to handle incoming HTTP requests.
         *
         * See https://genhttp.org/documentation/content/frameworks/controllers/
         *
         */

        return Layout.Create()
                     .AddController<BookController>("books");
    }

    public record Book(int Id, string Title);

    public class BookController
    {
        private const int MaxBooks = 50;

        private static readonly List<Book> Books =
        [
            new(1, "Lord of the Rings")
        ];

        // GET /samples/controllers/books/
        [ControllerAction(Method.Get)]
        public List<Book> Index()
        {
            lock (Books) return [..Books];
        }

        // PUT /samples/controllers/books/create/ with JSON/XML/... payload
        [ControllerAction(Method.Put)]
        public Book Create(Book book)
        {
            lock (Books)
            {
                if (Books.Count >= MaxBooks)
                {
                    throw new ProviderException(ResponseStatus.Conflict, "The shelf is full, please delete a book first");
                }

                var toAdd = book with
                {
                    Id = Books.Select(b => b.Id).DefaultIfEmpty().Max() + 1
                };

                Books.Add(toAdd);
                return toAdd;
            }
        }

        // DELETE /samples/controllers/books/delete/1/
        [ControllerAction(Method.Delete)]
        public void Delete([FromPath] int id)
        {
            lock (Books) Books.RemoveAll(b => b.Id == id);
        }

    }

}

Try it

Send the requests to the sample running on this server - change the path, headers or body as you like, or copy them as curl commands.

  1. List all books

    GET
    curl -i 'https://genhttp.org/samples/controllers/books/'
  2. Add a book

    PUT
    Headers and body
    curl -i -X PUT -H 'Content-Type: application/json' -d '{ "title": "The Hobbit" }' 'https://genhttp.org/samples/controllers/books/create/'
  3. Delete a book

    DELETE
    Headers and body
    curl -i -X DELETE 'https://genhttp.org/samples/controllers/books/delete/1/'