0

I have a basic custom AuthenticationHandler like in this post https://jasonwatmore.com/post/2018/09/08/aspnet-core-21-basic-authentication-tutorial-with-example-api

In the Task<AuthenticateResult> HandleAuthenticateAsync() override I need to to get the controller name.

Injecting IActionContextAccessor in the startup doesn't work:

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

The ActionContext property is null (not set yet I think)

HttpContext is available, so should i just try to parse the Context.Request.Path ?

Thanks in advance !

PBO
  • 1
  • 2
  • 1
    Does this answer your question? [Get controller and action name from AuthorizationHandlerContext object](https://stackoverflow.com/questions/41103694/get-controller-and-action-name-from-authorizationhandlercontext-object) – Matt U Dec 17 '19 at 15:09
  • are you looking for this: https://github.com/aspnet/mvc/issues/3936 ? – Dongdong Dec 17 '19 at 15:22
  • its an AuthenticationHandler which dont have a context.Resource property :( – PBO Dec 17 '19 at 15:22
  • 1
    @PBO can you post your code where you use `ActionContextAccessor`? have you tried `services.AddHttpContextAccessor();`? – Dongdong Dec 17 '19 at 16:12
  • can you show us more code? – phonemyatt Dec 18 '19 at 04:01
  • You won't get route data before the Router middleware is invoked.A workaround here is that try to add `app.UseEndpointRouting()` before `app.UseAuthentication()` ( Though it is not recommended ) or call router yourself .refer to https://stackoverflow.com/questions/58016881/getroutedata-always-null-using-aspnetcore-odata-7-2-1 – Ryan Dec 18 '19 at 10:01

1 Answers1

0

As I explained in the comment that you won't get route data before the Router middleware is invoked.

For your tutorial code,I find out a solution to create a router and make it runs before the Authentication middleware. In 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();
    }

Get controller name in AuthenticationaHandler (using Microsoft.AspNetCore.Routing reference):

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var name = Context.GetRouteValue("controller");
        //...
    }
Ryan
  • 19,118
  • 10
  • 37
  • 53