CORS

Live on this server

Allows a frontend on another origin to call the API from the browser.

CorsSample.cs45 lines
using System.Collections.Concurrent;

using GenHTTP.Api.Content;
using GenHTTP.Api.Protocol;

using GenHTTP.Modules.Functional;
using GenHTTP.Modules.Layouting;
using GenHTTP.Modules.Security;

public static class CorsSample
{

    public static IHandlerBuilder Create()
    {
        /*
         *
         * Allows a frontend hosted on another origin (e.g. a React app served by
         * the Vite dev server on http://localhost:5173) to call this API from the browser.
         * Browsers will block requests from any other origin.
         *
         * See https://genhttp.org/documentation/content/concerns/cors/
         *
         */

        var todos = new ConcurrentQueue<string>(["Write the frontend"]);

        var api = Inline.Create()
                        .Get(() => todos.ToList()) // GET /samples/cors/api/todos/
                        .Put((string todo) => // PUT /samples/cors/api/todos/?todo=...
                        {
                            todos.Enqueue(todo);

                            // keeps the latest todos only
                            while (todos.Count > 50) todos.TryDequeue(out _);
                        });

        var policy = CorsPolicy.Restrictive()
                               .Add("http://localhost:5173", [RequestMethod.Get, RequestMethod.Put], allowedHeaders: null, exposedHeaders: null, allowCredentials: false);

        return Layout.Create()
                     .Add("api/todos", api)
                     .Add(policy);
    }

}

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 the todos

    GET
    curl -i 'https://genhttp.org/samples/cors/api/todos/'
  2. Send the preflight request of the frontend

    Browsers send this before the actual request. Try another origin to see the CORS headers disappear.

    curl -i -X OPTIONS -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: PUT" https://genhttp.org/samples/cors/api/todos/