C
C#3y 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
Cisien3y ago
the primary message handler is something like HttpClientHandler or SocketHttpHandler
devhl
devhlOP3y ago
What makes it "primary"
Cisien
Cisien3y ago
it's the thing that does the work
devhl
devhlOP3y ago
lol okay
Cisien
Cisien3y ago
delegating handlers let you inject something in between
devhl
devhlOP3y ago
Oh perfect
Cisien
Cisien3y ago
so, in your case, changing the url, doing logging, perf counters, etc.
devhl
devhlOP3y ago
Then I'm in the right place then. Thanks for the help!
Cisien
Cisien3y ago
yep
Want results from more Discord servers?
Add your server