10

ASP.NET Core 6: Working with minimal APIs

 3 years ago
source link: https://anthonygiretti.com/2021/08/12/asp-net-core-6-working-with-minimal-apis/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ASP.NET Core 6: Working with minimal APIs

2021-08-12 by anthonygiretti

Introduction

ASP.NET Core 6 is taking shape and I’m already a fan of one of its new features, the one that allows you to create APIs with the minimum dependence on the WebAPI framework and the minimum code and files necessary for the development of minimalist APIs: minimal APIs, let’s see together how does it look like.

Create a minimal API project

There is no particular ASP.NET Core template to build a minimal API like Blazor or a webAPI, you can simply use the “ASP.NET Core Empty” template to create your project:

This template generates the following minimalist project:

The Startup.cs file has disappeared, only the Program.cs file and appsettings.json files remain. The great thing is that now the Program.cs file is generated by default with the Top-level programs feature brought by C# 9 last year.

The to understand here is that mininal APIs is a simplified mix between:

Nothing less nothing more!

Concrete example

On the next example, I’ll implement the following features taken from my ASP.NET WebAPI here: commonfeatures-webapi-aspnetcore/Startup.cs at master · AnthonyGiretti/commonfeatures-webapi-aspnetcore (github.com):

This is minimalist but it meets, most often, requirements for a single endpoint hats needs to be documented, protected by authentication and well designed with a service that needs to be abstracted in an interface, minimalist doesn’t mean that your code should not be well designed!

Here we go:

A simple service that returns some logic depending on some parameters:

namespace MinimalApiDemo.Services;

public interface IHelloService { string Hello(ClaimsPrincipal user, bool isHappy); }

public class HelloService : IHelloService { public string Hello(ClaimsPrincipal user, bool isHappy) { var hello = $"Hello {user.Identity.Name}";

if (isHappy) return $"{hello}, you seem to be happy today"; return hello; } }

The GlobalUsing.cs file designed for the ASP.NET Core 6 minimal API:

global using Microsoft.OpenApi.Models; global using MinimalApiDemo.Services; global using Microsoft.AspNetCore.Authentication.JwtBearer; global using System.Security.Claims;

And the Program.cs file:

// Configure services var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Authority = "https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxxxxxxxx"; options.Audience = "xxxxxxxxxxxxxxxxxxxxxxxxx"; options.TokenValidationParameters.ValidateLifetime = false; options.TokenValidationParameters.ClockSkew = TimeSpan.Zero; });

builder.Services.AddAuthorization();

builder.Services.AddCors();

builder.Services.AddScoped<IHelloService, HelloService>();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header,

}, new List<string>() }}); });

// Configure and enable middlewares var app = builder.Build();

if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); }

app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api v1"));

app.UseCors(p => { p.AllowAnyOrigin(); p.WithMethods("GET"); p.AllowAnyHeader(); });

app.UseAuthentication(); app.UseAuthorization();

// GET endpoint where IHelloService and ClaimsPrincipal and injected by dependency no needs to use anymore [FromServices] attribute // ClaimsPrincipal is automatically injected app.MapGet("/Hello", (bool? isHappy, IHelloService service, ClaimsPrincipal user) => { if (isHappy is null) return Results.BadRequest("Please tell if you are happy or not :-)");

return Results.Ok(service.Hello(user, (bool)isHappy)); }).RequireAuthorization();

// Run the app app.Run();

Note that in ASP.NET Core 6 mininum, route-to-code endpoints can manage easily HTTP statuses with the new static class Results. It can as well manage many kind of results such as Json, File, Text etc…. All these methods return a IResult, Here is the Results static class signature from the Microsoft.AspNetCore.Http assembly 6.0.0.0:

Last thing I really liked there is the dependency injection in minimal API, services don’t need anymore to be injected with the [FromService] attribute, and even more: when you are using Authentication feature, some user Identity objects are also injected automatically such as ClaimsPrincipal in the example there.

Let’s see a quick demo!

The following example shows a BadRequest reponse:

The following shows a Ok response:

And the following shows the failed Authentication with the UnAuthenticated response:

Conclusion

This example is simple but meetsmost of time minimal requirements, I did not show all the possibilities in all the scenarios offered by the minimal APIs, but my Github repository here: https://github.com/AnthonyGiretti/aspnetcore-minimal-api will regularly evolve, at the same time as I discover the miniamal APIs. If you want to contribute you are welcome!

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK