Search code examples
c#asp.net-identityminimal-apis

Getting the current user in a minimal api


I am trying to refactor my api into a minimal api. Previously I've been using ControllerBase.HttpContext to get the user like this:

var emial = HttpContext.User.FindFirstValue(ClaimTypes.Email);

The method that I want to use for my endpoint mapping should be something like this:

public static void MapSurveyEndpoints(this WebApplication app) {
    app.MapPost("/api/Surveys", AddSurveysAsync);
}

public static async Task<Survey> AddSurveysAsync(ISurveyRepository repo, Survey survey) {
    var email = ...; //get current user email
    survey.UserEmail = email;
    return await repo.AddSurveysAsync(survey);
}

What would be another approach for getting the user without using controller?


Solution

  • Minimal APIs have several parameter binding sources for handlers, including special types, like HttpContext as suggested in another answer, but if you need only the user info you can add just ClaimsPrincipal (which is one of the special types) parameter to your handler:

    app.MapGet("/...", (..., ClaimsPrincipal user) => user.Identity.Name);