C
C#2y ago
devhl

Middleware to modify url

I'm trying to modify my HttpClient so it modifies a url before sending. I think I see how to do it but I just want to check as I've never done this. Also, what is a primary message handler? How is primary different than any other message handler?
services.AddHttpClient("cocApi", config =>
{
config.BaseAddress = new Uri(hostBuilder.Configuration["Settings:BaseAddress"]);
})
.ConfigurePrimaryHttpMessageHandler(sp => new SocketsHttpHandler()
{
MaxConnectionsPerServer = 10
})
.AddHttpMessageHandler((services) => new Foo());
});
}

public class Foo : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("hi"); // this fires so i guess i got it right
return base.SendAsync(request, cancellationToken);
}
}
services.AddHttpClient("cocApi", config =>
{
config.BaseAddress = new Uri(hostBuilder.Configuration["Settings:BaseAddress"]);
})
.ConfigurePrimaryHttpMessageHandler(sp => new SocketsHttpHandler()
{
MaxConnectionsPerServer = 10
})
.AddHttpMessageHandler((services) => new Foo());
});
}

public class Foo : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("hi"); // this fires so i guess i got it right
return base.SendAsync(request, cancellationToken);
}
}
9 Replies
Cisien
Cisien2y ago
the primary message handler is something like HttpClientHandler or SocketHttpHandler
devhl
devhl2y ago
What makes it "primary"
Cisien
Cisien2y ago
it's the thing that does the work
devhl
devhl2y ago
lol okay
Cisien
Cisien2y ago
delegating handlers let you inject something in between
devhl
devhl2y ago
Oh perfect
Cisien
Cisien2y ago
so, in your case, changing the url, doing logging, perf counters, etc.
devhl
devhl2y ago
Then I'm in the right place then. Thanks for the help!
Cisien
Cisien2y ago
yep
Want results from more Discord servers?
Add your server
More Posts