![](/img/trans.png)
[英]Overriden HandleAuthenticateAsync method in AuthenticationHandler in ASP.Net Core Web Api is called twice with different headers
[英]Get controller name in AuthenticationHandler in asp.net core 2.2 web api
我有一个基本的自定义 AuthenticationHandler 就像这篇文章https://jasonwatmore.com/post/2018/09/08/aspnet-core-21-basic-authentication-tutorial-with-example-api
在Task<AuthenticateResult> HandleAuthenticateAsync()
覆盖中,我需要获取控制器名称。
在启动时注入 IActionContextAccessor 不起作用:
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
ActionContext 属性为空(我认为尚未设置)
HttpContext 可用,所以我应该尝试解析 Context.Request.Path 吗?
提前致谢 !
正如我在评论中解释的那样,在调用 Router 中间件之前您不会获得路由数据。
对于您的教程代码,我找到了创建路由器并使其在身份验证中间件之前运行的解决方案。 在启动.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseRouter(routeBuilder => {
var template = "{controller=Users}/{action=GetAll}/{id?}";
routeBuilder.MapMiddlewareRoute(template, appBuilder => {
appBuilder.UseAuthentication();
appBuilder.UseMvc();
});
});
//add more middlewares if you want other routes
app.UseAuthentication();
app.UseMvc();
}
在AuthenticationaHandler
获取控制器名称(使用 Microsoft.AspNetCore.Routing 参考):
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var name = Context.GetRouteValue("controller");
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.