Giter Site home page Giter Site logo

marcominerva / minimalhelpers Goto Github PK

View Code? Open in Web Editor NEW
90.0 6.0 3.0 112 KB

A collection of helpers libraries for Minimal API projects.

License: MIT License

C# 88.48% PowerShell 11.52%
aspnetcore minimalapi minimalapis minimal-api hacktoberfest net routing openapi swagger csharp visual-studio

minimalhelpers's Introduction

Minimal APIs Helpers

Lint Code Base License: MIT

A collection of helpers libraries for Minimal API projects.

MinimalHelpers.Routing

Nuget Nuget

A library that provides Routing helpers for Minimal API projects for automatic endpoints registration using Reflection.

Installation

The library is available on NuGet. Just search for MinimalHelpers.Routing in the Package Manager GUI or run the following command in the .NET CLI:

dotnet add package MinimalHelpers.Routing

Usage

Create a class to hold your route handlers registration and make it implementing the IEndpointRouteHandlerBuilder interface:

.NET 6.0

public class PeopleHandler : MinimalHelpers.Routing.IEndpointRouteHandlerBuilder
{
    public void MapEndpoints(IEndpointRouteBuilder endpoints)
    {
        endpoints.MapGet("/api/people", GetList);
        endpoints.MapGet("/api/people/{id:guid}", Get);
        endpoints.MapPost("/api/people", Insert);
        endpoints.MapPut("/api/people/{id:guid}", Update);
        endpoints.MapDelete("/api/people/{id:guid}", Delete);
    }

    // ...
}

.NET 7.0 or higher

public class PeopleHandler : MinimalHelpers.Routing.IEndpointRouteHandlerBuilder
{
    public static void MapEndpoints(IEndpointRouteBuilder endpoints)
    {
        endpoints.MapGet("/api/people", GetList);
        endpoints.MapGet("/api/people/{id:guid}", Get);
        endpoints.MapPost("/api/people", Insert);
        endpoints.MapPut("/api/people/{id:guid}", Update);
        endpoints.MapDelete("/api/people/{id:guid}", Delete);
    }

    // ...
}

Note Starting from .NET 7.0, the IEndpointRouteHandlerBuilder interface exposes the MapEndpoints method as static abstract, so it can be called without creating an instance of the handler.

Call the MapEndpoints() extension method on the WebApplication object inside Program.cs before the Run() method invocation:

// using MinimalHelpers.Routing;
app.MapEndpoints();

app.Run();

By default, MapEndpoints() will scan the calling Assembly to search for classes that implement the IEndpointRouteHandlerBuilder interface. If your route handlers are defined in another Assembly, you have two alternatives:

  • Use the MapEndpoints() overload that takes the Assembly to scan as argument
  • Use the MapEndpointsFromAssemblyContaining<T>() extension method and specify a type that is contained in the Assembly you want to scan

You can also explicitly decide what types (among the ones that implement the IRouteEndpointHandlerBuilder interface) you want to actually map, passing a predicate to the MapEndpoints method:

app.MapEndpoints(type =>
{
    if (type.Name.StartsWith("Products"))
    {
        return false;
    }

    return true;
});

Note These methods rely on Reflection to scan the Assembly and find the classes that implement the IEndpointRouteHandlerBuilder interface. This can have a performance impact, especially in large projects. If you have performance issues, consider using the explicit registration method. Moreover, this solution is incompatibile with Native AOT.

If you're working with .NET 7.0 or higher, the reccommended approach is to use the MinimalHelpers.Routing.Analyzers package, that provides a Source Generator for endpoints registration, as described later.

MinimalHelpers.Routing.Analyzers (.NET 7.0 or higher)

Nuget Nuget

A library that provides a Source Generator for automatic endpoints registration in Minimal API projects.

Installation

The library is available on NuGet. Just search for MinimalHelpers.Routing in the Package Manager GUI or run the following command in the .NET CLI:

dotnet add package MinimalHelpers.Routing.Analyzers

Usage

Create a class to hold your route handlers registration and make it implementing the IEndpointRouteHandlerBuilder interface:

public class PeopleHandler : IEndpointRouteHandlerBuilder
{
    public static void MapEndpoints(IEndpointRouteBuilder endpoints)
    {
        endpoints.MapGet("/api/people", GetList);
        endpoints.MapGet("/api/people/{id:guid}", Get);
        endpoints.MapPost("/api/people", Insert);
        endpoints.MapPut("/api/people/{id:guid}", Update);
        endpoints.MapDelete("/api/people/{id:guid}", Delete);
    }

    // ...
}

Note You only need to use the MinimalHelpers.Routing.Analyzers package. With this Source Generator, the IEndpointRouteHandlerBuilder interface is auto-generated.

Call the MapEndpoints() extension method on the WebApplication object inside Program.cs before the Run() method invocation:

app.MapEndpoints();

app.Run();

Note The MapEndpoints method is generated by the Source Generator.

MinimalHelpers.OpenApi

Nuget Nuget

A library that provides OpenApi helpers for Minimal API projects.

Installation

The library is available on NuGet. Just search for MinimalHelpers.OpenApi in the Package Manager GUI or run the following command in the .NET CLI:

dotnet add package MinimalHelpers.OpenApi

Usage

Add OpenApi support for IFormFile and IFormFileCollection

Minimal APIs don't generate the correct schema in swagger.json if we have an endpoint that accepts a IFormFile or IFormFileCollection parameter and we're using the WithOpenApi extension method in .NET 7.0 or later. For example:

app.MapPost("/api/upload", (IFormFile file) =>
{
    return TypedResults.Ok(new { file.FileName, file.ContentType, file.Length });
})
.WithOpenApi();

This definition generates the following incorrect content in swagger.json:

"requestBody": {
    "content": {
        "multipart/form-data": {
            "schema": {
                "type": "string",
                "format": "binary"
            }
        }
    },
    "required": true
}

To solve this issue, just call the following extension method:

builder.Services.AddSwaggerGen(options =>
{
    // using MinimalHelpers.OpenApi;
    options.AddFormFile();
});

And now the IFormFile is correctly defined:

"requestBody": {
  "content": {
    "multipart/form-data": {
      "schema": {
        "required": [
          "file"
        ],
        "type": "object",
        "properties": {
          "file": {
            "type": "string",
            "format": "binary"
          }
        }
      },
      "encoding": {
        "file": {
          "style": "form"
        }
      }
    }
  }
}

Add missing schema in swagger.json (.NET 7.0)

Minimal APIs in .NET 7.0 don't generate the correct schema in swagger.json for certain file types, like Guid, DateTime, DateOnly and TimeOnly when using the WithOpenApi extension method on endpoints. For example, given the following endpoint:

    app.MapGet("/api/schemas",
        (Guid id, DateTime dateTime, DateOnly date, TimeOnly time) => TypedResults.NoContent());

swagger.json will not contain format specification for these data types (whereas Controllers correctly set them):

"parameters": [
  {
    "name": "id",
    // ...
    "schema": {
      "type": "string"
    }
  },
  {
    "name": "dateTime",
    // ...
    "schema": {
      "type": "string"
    }
  },
  {
    "name": "date",
    // ...
    "schema": {
      "type": "string"
    }
  },
  {
    "name": "time",
    // ...
    "schema": {
      "type": "string"
    }
  }
]

To solve these issues, just call the following extension method:

builder.Services.AddSwaggerGen(options =>
{
    // using MinimalHelpers.OpenApi;
    options.AddMissingSchemas();
});

And you'll see that the correct format attribute has been specified for each parameter.

"parameters": [
  {
    "name": "id",
    // ...
    "schema": {
      "type": "string",
      "format": "uuid"
    }
  },
  {
    "name": "dateTime",
    // ...
    "schema": {
      "type": "string",
      "format": "date-time"
    }
  },
  {
    "name": "date",
    // ...
    "schema": {
      "type": "string",
      "format": "date"
    }
  },
  {
    "name": "time",
    // ...
    "schema": {
      "type": "string",
      "format": "time"
    }
  }
]    

Note This workaround is no longer necessary in .NET 8.0 or higher, since it correctly sets in the format attribute in swagger.json for these data types.

Contribute

The project is constantly evolving. Contributions are welcome. Feel free to file issues and pull requests on the repo and we'll address them as we can.

minimalhelpers's People

Contributors

kasuken avatar marcominerva avatar mhartvig avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

minimalhelpers's Issues

Provide a static abstract interface method to register endpoints

Currently, the library requires that we implement the IEndpointRouteHandler interface and, at runtime, reflection is used to instantiate the class in order to call the MapEndpoints method. With .NET 7.0, we can provide an alternative method to endpoint registration using static abstract interface members. The proposal is to add the following interface and the corresponding extension method to the library:

public interface IStaticEndpointRouteHandler
{
    static abstract void MapEndpoints(IEndpointRouteBuilder endpoints);
}

public static void MapEndpoints<T>(this IEndpointRouteBuilder endpoints) where T : IStaticEndpointRouteHandler
{
     // ...
}

In this way, we can register our handler using a syntax like this:

app.MapEndpoints<PeopleHandler>();
app.MapEndpoints<ProductsHandler>();

And no reflection at all will be involved in the registration process.

The question is: giving this new behavior, do you think that IStaticEndpointRouteHandler is a good name for the new interface?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.