Home > Mobile >  Getting the current user in a minimal api
Getting the current user in a minimal api

Time:11-09

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?

CodePudding user response:

You can take the HttpContext as a parameter of your endpoint. ASP.NET Core will then provide that to you.

public static async Task<Survey> AddSurveysAsync(
    HttpContext context,
    ISurveyRepository repo,
    Survey survey)

CodePudding user response:

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

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