Middleware and Attributes to simplify Minimal API Development
License
—
Deps
0
Install Size
—
Vulns
✓ 0
Published
Dec 10, 2022
$ dotnet add package Selfrated.MinimalAPI.MiddlewareA set of tools to simplify creating ASPNetCore applications, specifically when using MinimalAPIs.
The middleware helps clean up your code by making it easy to break the application startup into seperate classes, ideally named by what their purpose is.
and ASPNetCore applications, with at least .NET 7.0
dotnet add package Selfrated.MinimalAPI.Middleware
By utilizing these attributes, you can quickly and easily get endpoints created from any file that uses them. By default the names of the classes/methods will be the names of the endpoints, requiring as little code/effort as possible.
This is a fully functional file that will create a fully functional endpoint for /Sample/TestEndpoint (i.e. https://localhost:7000/Sample/TestEndpoint)!
using Selfrated.MinimalAPI.Middleware.Attributes;
namespace WebApplication1.Endpoints;
[EndpointAPI]
public class Sample
{
[EndpointMethod]
public string TestEndpoint()
{
return "Hello World!";
}
}
Any class that has wants to expose an endpoint will need to have this attribute defined.
[EndpointAPI(Name = "NewPrefix", AuthenticationRequired = AuthenticationRequired.Yes)]
By using this on any method in a class that uses EndpointAPIAttribute, it will create an endpoint just like that!
[EndpointMethod(Name = "NewName", RouteType = RouteType.POST | RouteType.PUT)]
Any objects that implement IBuilderServiceSetup and/or IApplicationSetup will be processed when the WebApplication is built. This happens once, when the applcation starts.
The following sample file (Authentication.cs) sets up azure AD authentication with the application.
public class Authentication : IApplicationSetup, IBuilderServiceSetup
{
public void InitializeApplication(WebApplication app)
{
app.UseAuthentication();
app.UseAuthorization();
}
public void InitializeServices(IServiceCollection services, ConfigurationManager configuration, ConfigureHostBuilder host)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
configuration.Bind("AzureAd", options);
},
options => { configuration.Bind("AzureAd", options); });
}
}
This is a complete Program.cs file!
var builder = WebApplication.CreateBuilder(args);
//if using IBuilderServiceSetup
builder.UseBuilderSetup();
var app = builder.Build();
//if using IApplicationSetup
app.UseApplicationSetup();
//if using EndpointAttributes (Minimal API)
app.UseEndpointsAPIAttributes();
app.Run();