.NET 7 is loaded with new features and specially covering Minimal API features like Endpoint Filters,
Route groups, Authentication Improvements, Endpoint metadata providers and
Unit Testing. This PPT covers the basics of API, Minimal API and new features.
If you're new to API and Minimal, you should be able to understand everything.
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
New features of Minimal APIs in .NET 7 -Muralidharan Deenathayalan.pptx
1. Coimbatore, India January 21, 2023
Brought to you by
PRESENTS
.Net Conf 2022
Muralidharan Deenathayalan
New features of Minimal APIs in .NET 7
Digital Transformation | Power Platform | SharePoint | Machine
Learning
2. Brought to you by
Muralidharan Deenathayalan
LinkedIn : https://www.linkedin.com/in/muralidharand/
Twitter : https://twitter.com/muralidharand
GitHub : https://github.com/muralidharand
Blog : www.codingfreaks.net
3. Brought to you by
Agenda
API Introduction
Getting started with Minimal API
ASP .NET API vs Minimal API
Advantages of Minimal API
Disadvantages of Minimal API
New features of Minimal API in .NET 7
Demo
Q & A
4. Brought to you by
API Introduction
Communication between two applications
5. Brought to you by
API Introduction
Database Web Server API Internet Web App 2
Web App 3
Web App 1
6. Brought to you by
Getting started with Minimal API
Simplified approach
Faster APIs
Minimal code and configurations
No traditional scaffolding is required
No controllers and actions overhead
Minimal != simple
7. Brought to you by
Getting started with Minimal API
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
8. Brought to you by
Getting started with Minimal API
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/users/{userId}/books/{bookId}", (int userId, int
bookId) => $"The user id is {userId} and book id is {bookId}");
app.Run();
9. Brought to you by
ASP .NET API vs Minimal API
Minimal API ASP.NET API
Single file based approach Class files are separated in Models, Controllers
and Views
Granular control on your API MVC takes more control
Minimum components are required to build API Relies on Controller, Model and Views
Better performance Good performance
Easy to learn by new developers Need to understand the basics like Models,
Controllers and Views.
PROS
10. Brought to you by
ASP .NET API vs Minimal API
Minimal API ASP.NET API
Leads to poorly managed code in a single file Controller, Model are exist in different files
Need to implement validation explicitly Model validation supported by default
Structure is not matured, evolving Matured structed
Preferred to build Lightweight API Preferred to build complex APIs
New features are added slowly Great features of out-of-box
CONS
11. Brought to you by
Advantages of Minimal API
Easy to get started
Easy and build faster, POC
Ideal for building Microservices API
Granular control
Can be easily adopted by new developers
Less code makes faster compile time
12. Brought to you by
Disadvantages of Minimal API
Implement custom model validation
Adding more code lead increases complexity
Not all features are supported comparatively ASP.NET MVC API
Can be easily adopted by new developers
Less code makes faster compile time
13. Brought to you by
New features of Minimal API in .NET 7
Endpoint Filters
Route groups
Authentication Improvements
Endpoint metadata providers
Unit Testing
14. Brought to you by
Endpoint Filters
Business logics can be implemented before the actual code executes
Modify the input params during endpoint filter processing
Logging the input param details
Modify the response before returning
IEndpointFilter – Interface needs to implemented, like IActionFilter
BeforeEndpoint Execution
Short-circuit Execution
AfterEndpoint Execution
15. Brought to you by
Endpoint Filters
namespace Microsoft.AspNetCore.Http;
public interface IEndpointFilter
{
ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next);
}
app.MapGet("/student/{name?}", (string? name) =>
new MyResult(name ?? "Hi!"))
.AddEndpointFilter<FILTER_CLASS_NAME>();
Attach your Endpoint filter here
16. Brought to you by
BeforeEndpoint Execution Filter
public class BeforeEndpointExecution : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
if (context.HttpContext.GetRouteValue("name") is string name)
{
return Results.Ok($"Hi {name}, this is from the filter!");
}
return await next(context);
}
}
app.MapGet("/student/{name?}", (string? name) => new MyResult(name ??
"Hi!"))
.AddEndpointFilter<BeforeEndpointExecution>();
17. Brought to you by
Short-Circuit Execution Filter
public class ShortCircuit : IEndpointFilter
{
public ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
return new ValueTask<object?>(Results.Json(new { Name = "hello" }));
}
}
app.MapGet("/student/{name?}", (string? name) => new MyResult(name ??
"Hi!"))
.AddEndpointFilter<ShortCircuit>();
18. Brought to you by
AfterEndpoint Execution Filter
app.MapGet("/student/{name?}", (string? name) =>
new MyResult(name ?? "Hi!"))
.AddEndpointFilter<AfterEndpointExecution>();
public class AfterEndpointExecution : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,EndpointFilterDelegate next){
var result = await next(context);
if (result is MyResultWithEndpoint dp &&
context.HttpContext.GetEndpoint() is { } e)
{ dp.EndpointDisplayName = e.DisplayName ?? "";}
return result;
}
}
19. Brought to you by
Endpoint Filters
BeforeEndpoint filter will be executed in FIFO (First In, First Out)
AfterEndpoint filter will be executed in FILO (First In, Last Out)
Points to be remembered
20. Brought to you by
Route groups
MapGroups – Extension method for grouping common endpoints.
Applying RequireAuthentication() or any other endpoint filter will be
applied all group member methods.
MapGroups can be nested.
21. Brought to you by
Route groups
app.MapGroup("/public/todos")
.MapTodosApi();
public static RouteGroupBuilder MapTodosApi
(this RouteGroupBuilder group)
{
group.MapGet("/", () => "Hello route");
group.MapGet("/{id}", () => "Hello route");
group.MapPost("/", () => "Hello route");
group.MapPut("/{id}", () => "Hello route");
group.MapDelete("/{id}", () => "Hello route");
return group;
}
22. Brought to you by
Route groups
app.MapGroup("/public/todos")
.MapTodosApi().RequireAuthorization();
public static RouteGroupBuilder MapTodosApi
(this RouteGroupBuilder group)
{
group.MapGet("/", () => "Hello route");
group.MapGet("/{id}", () => "Hello route");
group.MapPost("/", () => "Hello route");
group.MapPut("/{id}", () => "Hello route");
group.MapDelete("/{id}", () => "Hello route");
return group;
}
23. Brought to you by
Authentication Improvements
Default Authentication Scheme
Simplified Authentication Configuration
Authorization Policies for Specific Endpoints
New user-jwts tool
24. Brought to you by
Default Authentication Scheme
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationS
cheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options
=>
{
//actual code goes here
});
builder.Services.AddAuthentication() //👈 no default scheme
specified
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options
=>
{
//actual code goes here
});
.NET 6
.NET 7
25. Brought to you by
Simplified Authentication Configuration
.NET 6
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options
=>
{
options.Authority =
$"https://{builder.Configuration["My:Domain"]}";
options.TokenValidationParameters =
new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudience = builder.Configuration["My:Audience"],
ValidIssuer = $"{builder.Configuration["My:Domain"]}"
};
});
26. Brought to you by
Simplified Authentication Configuration
.NET 7
builder.Services.AddAuthentication().AddJwtBearer(); //👈 new feature
appsetting.json
{
"AllowedHosts": "*",
"Authentication": {
"Schemes": {
"Bearer": {
"Authority": "https://YOUR_AUTH0_DOMAIN",
"ValidAudiences": [ "YOUR_AUDIENCE" ],
"ValidIssuer": "YOUR_AUTH0_DOMAIN"
}
}
}
}
27. Brought to you by
Simplified Authentication Configuration
.NET 7
builder.Services.AddAuthentication().AddJwtBearer(); //👈 new feature
appsetting.json
{
"AllowedHosts": "*",
"Authentication": {
"DefaultScheme" : "JwtBearer",
"Schemes": {
"JwtBearer": {
"Audiences": [ "http://localhost:5000", "https://localhost:5001" ],
"ClaimsIssuer": "dotnet-user-jwts"
}
}
}
}
28. Brought to you by
Authorization Policies for Specific
Endpoints
app.MapGet("/api/hello", () => "Hello!")
.RequireAuthorization(p => p.RequireClaim("scope",
"api:admin"));
29. Brought to you by
user-jwts tool
dotnet user-jwts create
32. Brought to you by
Muralidharan Deenathayalan
LinkedIn : https://www.linkedin.com/in/muralidharand/
Twitter : https://twitter.com/muralidharand
GitHub : https://github.com/muralidharand
Blog : www.codingfreaks.net