.NET 6.0 Web API中Minimal API如何获取当前用户信息
在.NET 6 Minimal API中读取JWT Claim的用户信息
你已经完成了.NET 6 REST API的JWT认证配置,在ControllerBase中可以正常通过this.User获取用户Claim,但在Minimal API的app.MapGet委托里无法直接使用该方式——原因是Minimal API没有ControllerBase内置的User属性,需要通过显式注入上下文对象来获取用户信息,以下是两种可行方案:
方案一:直接注入ClaimsPrincipal参数
在MapGet的委托方法中声明ClaimsPrincipal类型的参数,ASP.NET Core框架会自动将当前认证用户的主体信息注入进来:
app.MapGet("/Locations", [Authorize] (ClaimsPrincipal user) => { // 安全获取用户ID,避免空引用异常 string userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty; return MyMethods.GetLocations(builder, userId); });
方案二:通过HttpContext获取
如果需要访问更多请求上下文信息,可以注入HttpContext,再通过其User属性获取用户Claim:
app.MapGet("/Locations", [Authorize] (HttpContext context) => { string userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? string.Empty; return MyMethods.GetLocations(builder, userId); });
关键注意事项
确保你在构建应用后,已经启用了认证和授权中间件(顺序不能颠倒),否则认证逻辑不会生效:
var app = builder.Build(); // 必须添加这两行,先认证后授权 app.UseAuthentication(); app.UseAuthorization(); // 其他中间件配置... app.Run();
内容的提问来源于stack exchange,提问作者Kiki
相关产品推荐
相关产品推荐

