【问题标题】:Get controller name in AuthenticationHandler in asp.net core 2.2 web api在asp.net core 2.2 web api中的AuthenticationHandler中获取控制器名称
【发布时间】:2019-12-17 15:05:42
【问题描述】:

我有一个基本的自定义 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 吗?

提前致谢!

【问题讨论】:

标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

正如我在评论中解释的那样,在调用路由器中间件之前您不会获得路由数据。

对于您的教程代码,我找到了创建路由器并使其在身份验证中间件之前运行的解决方案。在startup.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");
        //...
    }

【讨论】:

    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2022-08-18
    • 2020-02-18
    • 1970-01-01
    相关资源
    最近更新 更多