Home - PjMitchell/Easy.Endpoints GitHub Wiki

Easy.Endpoints

Aspnetcore endpoints without the controller. Define individual endpoint and endpoint handlers.

Install

dotnet add package Easy.Endpoints

Setup

Add Easy.Endpoint services

    services.AddRequestEndpoints();

Add Easy.Endpoint to the application builder

app.UseEndpoints(endpoints =>  
  {  
    endpoints.AddEasyEndpoints();  
  });

Will scan for implementations of IEndpoint and wire them into routing

IEndpoint

public interface IEndpoint {}

Expects there to be a Handle or HandleAsync method.

Parameters

  • Predefined request objects can be used: HttpContext, HttpRequest, HttpResponse, ClaimsPrincipal & CancellationToken
  • Route and Query params: bool, byte, u/short, u/int, u/long, float, double, decimal, Guid, Date/Time/Offset
  • Object not matching these will be expected to be retrieved from the body as Json

Return Object

  • void/Task: 201 response
  • string: 200 plain text response
  • IEndpointResult: will be handle by the IEndpointResult
  • object: 200 & json

Routing

Can apply routing and methods via attributes.

[Get("TestRoute/{id:int}")]
public class SampleEndpoint : IEndpoint
{  
    Task<Result> HandleAsync(int id, CancellationToken requestAborted);  
}  

Default routing pattern is "[endpoint]".
Conventions:

  • [endpoint] Endpoint Name trimmed for verb and Endpoint e.g
    • GetPeopleEndpoint: GET: [endpoint] = People,
    • PostPeopleEndpointHandler: POST: [endpoint] = People
  • [controller] Defined by [EndpointController("ControllerName")]
  • [type] Defined when using generic endpoints

Generic handler

Can declare generic handlers that can build routes for types
POST: /Animal/Cow
POST: /Animal/Dog

[EndpointController("Animal")]
[KnownTypes("Cow", typeof(Cow))]
[KnownTypes("Dog", typeof(Dog))]
[Post("[controller]/[type]")]
public class AnimalEndpointHandler<TAnimal> : IEndpoint where TAnimal : IAnimal
{
    public Task<string> HandleAsync(TAnimal body, CancellationToken cancellationToken)
    {
        return Task.FromResult(body.Says());
    }
}
⚠️ **GitHub.com Fallback** ⚠️