简体   繁体   中英

How does .NET Core C# Minimal API fill parameters?

With minimalistic API how does MapGet automatically fill parameters from querystring?

With minimalistic API the following is possible:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("api/Students/Grades", StudentsDataContext.GetGradesAsync).RequireAuthorization("Admin");

//...

public class Grade
{
    public string? Subject { get; set; }
    public int GradePercentage { get; set; } = 0;
}

public class StudentsDataContext
{
    public static async Task<List<Grade>> GetGradesAsync(int? studentId, ClaimsPrincipal user, CancellationToken ct))
    {
        // Gets grades from database...
        return new List<Grade>() {
              new () { Subject = "Algebra", GradePercentage=95 },
              new () { Subject = "English", GradePercentage=90 }
        };
    }
}

When you call: /api/Students/Grades?studentId=5 magically, studentId is passed to the GetGradesAsync, as well as ClaimsPrinicipal, and CancellationToken. 在此处输入图像描述

How does this witchcraft work? Is it possible to learn this power of the darkside?

The link you have provided describes the rules of the parameter binding in Minimal APIs. In the nutshell it is pretty simple - the request handler delegate is analyzed (via some reflection+runtime code generation or source generation at build time I suppose) and actual handler is created were all parameters are processed accordingly and passed to user defined one.

I have not spend much time so the following can be not entirely correct, but the starting point of the investigation how does it actually work would be EndpointRouteBuilderExtensions which leads to RequestDelegateFactory (see AddRouteHandler call which fills List<RouteEntry> _routeEntries which is later processed with CreateRouteEndpointBuilder method, which calls CreateHandlerRequestDelegate ) which should contain all the actual "magic".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM