question

techwatching avatar image
0 Votes"
techwatching asked techwatching commented

Restrict use of DelegatingHandler to specific routes.

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.

dotnet-csharpdotnet-aspnet-core-general
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

miwan2-msft avatar image
0 Votes"
miwan2-msft answered techwatching commented

Hi, @techwatching

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



image.png (11.5 KiB)
image.png (10.5 KiB)
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

If I understand correctly what you are suggesting me to do is to put my condition in my delegating handler which is precisely what I dont what to do:

I could do a condition if my handler's code but I am looking for a cleaner solution

There is a lot of reasons why I would prefer to have this condition outside of my delegating handler:
- separate concerns, my delegating handler should only do one thing : add a token bearer or another behavior, but not decide if it should apply or not
- I could want to reuse my handler elsewhere without the same conditions
- when I look at my startup it would be nice to know when a handler apply or not without having to dig into code

0 Votes 0 ·

By the way I don't really understand why you are copying and pasting phrases word to word from the Microsoft documentation not really relevant to my question:

In your preceding code, the ValidateHeaderHandler is registered with DI. Once registered, AddHttpMessageHandler will be called, passing in the type for the handler.

1 Vote 1 ·

Sorry for the unconsidered answer and I already post a new workaround. Hope it can help you.

0 Votes 0 ·
Show more comments