Restrict use of DelegatingHandler to specific routes.

Alexandre 346 Reputation points
2021-03-08T10:11:27.62+00:00

I am using a delegating handler to handle authentication of my http requests but I would like the handler to apply only on specific routes and not others. I could do a condition if my handler's code but I am looking for a cleaner solution.
The code in my Startup.cs look like that :

services.AddHttpClient<IMyService,MyService>()
             .AddHttpMessageHandler<AuthHandler>();

I was hoping to find an overload of AddHttpMessageHandler to specify on which routes I want that to apply or something like that.

In my use case, I don't want my httpclient to use the auth handler when the http request is to a route starting by /app and want it on routes starting by /auth.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,165 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Wang-MSFT 1,051 Reputation points
    2021-03-09T09:09:21.787+00:00

    Hi, @Alexandre

    You could only put condition into the overrided delegating handler to decide next operation. In your preceding code, the ValidateHeaderHandler is registered with DI. Once registered, AddHttpMessageHandler will be called, passing in the type for the handler.

    ---
    I think you are looking for a RouterMiddleware for the specific route middleware.

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
            {  
                ....  
      
                app.UseRouter(BuildRouter(app));  
      
                app.UseRouting();  
      
                ...  
            }  
      
            public IRouter BuildRouter(IApplicationBuilder applicationBuilder)  
            {  
                var builder = new RouteBuilder(applicationBuilder);  
      
                // use middlewares to configure a route  
                builder.MapMiddlewareGet("/api/v1/user", appBuilder => {  
                    // adds RequestValidationMiddleware delegate to the application's request pipeline and pass the request to next middleware.  
                    appBuilder.Use(RequestValidationMiddleware);  
                });  
      
                builder.MapMiddlewareGet("/api/v2/user", appBuilder => {  
                    // adds a middleware to the application's request pipeline and end the request.  
                    appBuilder.Run(async context => {  
                        await context.Response.WriteAsync("<div>/api/v2/user - Run</div>");  
                    });  
                });  
    
               // builder.MapMiddlewarePost("/api/v2/user"...  
    
                return builder.Build();  
            }  
      
            private Func<RequestDelegate, RequestDelegate> RequestValidationMiddleware = next => {  
                return async context =>  
                {  
                    await context.Response.WriteAsync("<div>/api/v1/user - RequestValidationMiddleware - Use</div>");  
                    await next(context);  
                };  
            };  
    

    Test result

    77543-image.png
    77508-image.png

    ---
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Michael Wang