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 :

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)

Leave a Reply