繁体   English   中英

以最小的方式获取当前用户 api

[英]Getting the current user in a minimal api

我正在尝试将我的 api 重构为最小的 api。以前我一直在使用 ControllerBase.HttpContext 来获取这样的用户:

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

我想用于我的端点映射的方法应该是这样的:

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);
}

在不使用 controller 的情况下获取用户的另一种方法是什么?

您可以将HttpContext作为端点的参数。 ASP.NET Core 将提供给您。

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

最小 API 有几个用于处理程序的参数绑定源,包括特殊类型,如另一个答案中建议的HttpContext ,但如果您只需要用户信息,您可以只向您的方法添加ClaimsPrincipal (这是一种特殊类型)参数:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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