HttpClientFactory with dynamic configurations
I am working on .net core web app which needs to call remote APIs at specific intervals(every 2 mins, 20 different API calls & I need to show API results to end users), hosted with 4 different domain names
I used HttpClient to call remote APIs. But with increased users, my CPU usage increased up to 40%. I suspect HttpClient might be the reason. After going through few blogs, I am trying to use HttpClientFactory.
I have a single method which gets call from Controller Action & I need to dynamically identify the BaseUrl based on few parameters. Currently I have created 4 NamedClients in StartUp.cs like this:
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl1, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl1").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
}).SetHandlerLifetime(TimeSpan.FromMinutes(5));
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl2, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl2").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
});
And then using in class like this:
public class Service : IService
{
private readonly IHttpClientFactory httpClientFactory;
public Service(IHttpClientFactory clientFactory)
{
httpClientFactory = clientFactory;
}
public HttpResponseMessage GetApiClientResponse(string displayName, IConfiguration configuration, HttpRequest httpRequest)
{
var endPoint = ApiConfig.GetApiDetail(configuration).
SingleOrDefault(ep => ep.DisplayName.ToLower().Equals(displayName.ToLower()));
var client = httpClientFactory.CreateClient(endPoint.NamedClient);
HttpResponseMessage response = null;
try
{
response = client.GetAsync(new Uri(endPoint.EndPointName,UriKind.Relative), HttpCompletionOption.ResponseHeadersRead).Result;
}
catch { ...}
return response;
}
}
here, based on the displayname parameter, I can decide which NamedClient is to be used.
Is there any other efficient way to achieve required functionality? Can I use TypedClient instead?
asp.net-core-2.1 .net-core-2.1 httpclientfactory
add a comment |
I am working on .net core web app which needs to call remote APIs at specific intervals(every 2 mins, 20 different API calls & I need to show API results to end users), hosted with 4 different domain names
I used HttpClient to call remote APIs. But with increased users, my CPU usage increased up to 40%. I suspect HttpClient might be the reason. After going through few blogs, I am trying to use HttpClientFactory.
I have a single method which gets call from Controller Action & I need to dynamically identify the BaseUrl based on few parameters. Currently I have created 4 NamedClients in StartUp.cs like this:
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl1, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl1").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
}).SetHandlerLifetime(TimeSpan.FromMinutes(5));
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl2, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl2").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
});
And then using in class like this:
public class Service : IService
{
private readonly IHttpClientFactory httpClientFactory;
public Service(IHttpClientFactory clientFactory)
{
httpClientFactory = clientFactory;
}
public HttpResponseMessage GetApiClientResponse(string displayName, IConfiguration configuration, HttpRequest httpRequest)
{
var endPoint = ApiConfig.GetApiDetail(configuration).
SingleOrDefault(ep => ep.DisplayName.ToLower().Equals(displayName.ToLower()));
var client = httpClientFactory.CreateClient(endPoint.NamedClient);
HttpResponseMessage response = null;
try
{
response = client.GetAsync(new Uri(endPoint.EndPointName,UriKind.Relative), HttpCompletionOption.ResponseHeadersRead).Result;
}
catch { ...}
return response;
}
}
here, based on the displayname parameter, I can decide which NamedClient is to be used.
Is there any other efficient way to achieve required functionality? Can I use TypedClient instead?
asp.net-core-2.1 .net-core-2.1 httpclientfactory
Can I use Single TypedClient with multiple different Base Urls?
– Priya
Nov 14 '18 at 14:59
add a comment |
I am working on .net core web app which needs to call remote APIs at specific intervals(every 2 mins, 20 different API calls & I need to show API results to end users), hosted with 4 different domain names
I used HttpClient to call remote APIs. But with increased users, my CPU usage increased up to 40%. I suspect HttpClient might be the reason. After going through few blogs, I am trying to use HttpClientFactory.
I have a single method which gets call from Controller Action & I need to dynamically identify the BaseUrl based on few parameters. Currently I have created 4 NamedClients in StartUp.cs like this:
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl1, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl1").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
}).SetHandlerLifetime(TimeSpan.FromMinutes(5));
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl2, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl2").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
});
And then using in class like this:
public class Service : IService
{
private readonly IHttpClientFactory httpClientFactory;
public Service(IHttpClientFactory clientFactory)
{
httpClientFactory = clientFactory;
}
public HttpResponseMessage GetApiClientResponse(string displayName, IConfiguration configuration, HttpRequest httpRequest)
{
var endPoint = ApiConfig.GetApiDetail(configuration).
SingleOrDefault(ep => ep.DisplayName.ToLower().Equals(displayName.ToLower()));
var client = httpClientFactory.CreateClient(endPoint.NamedClient);
HttpResponseMessage response = null;
try
{
response = client.GetAsync(new Uri(endPoint.EndPointName,UriKind.Relative), HttpCompletionOption.ResponseHeadersRead).Result;
}
catch { ...}
return response;
}
}
here, based on the displayname parameter, I can decide which NamedClient is to be used.
Is there any other efficient way to achieve required functionality? Can I use TypedClient instead?
asp.net-core-2.1 .net-core-2.1 httpclientfactory
I am working on .net core web app which needs to call remote APIs at specific intervals(every 2 mins, 20 different API calls & I need to show API results to end users), hosted with 4 different domain names
I used HttpClient to call remote APIs. But with increased users, my CPU usage increased up to 40%. I suspect HttpClient might be the reason. After going through few blogs, I am trying to use HttpClientFactory.
I have a single method which gets call from Controller Action & I need to dynamically identify the BaseUrl based on few parameters. Currently I have created 4 NamedClients in StartUp.cs like this:
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl1, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl1").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
}).SetHandlerLifetime(TimeSpan.FromMinutes(5));
services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl2, client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl2").Value);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
var userAgent = "C# app";
client.DefaultRequestHeaders.Add("User-Agent", userAgent);
});
And then using in class like this:
public class Service : IService
{
private readonly IHttpClientFactory httpClientFactory;
public Service(IHttpClientFactory clientFactory)
{
httpClientFactory = clientFactory;
}
public HttpResponseMessage GetApiClientResponse(string displayName, IConfiguration configuration, HttpRequest httpRequest)
{
var endPoint = ApiConfig.GetApiDetail(configuration).
SingleOrDefault(ep => ep.DisplayName.ToLower().Equals(displayName.ToLower()));
var client = httpClientFactory.CreateClient(endPoint.NamedClient);
HttpResponseMessage response = null;
try
{
response = client.GetAsync(new Uri(endPoint.EndPointName,UriKind.Relative), HttpCompletionOption.ResponseHeadersRead).Result;
}
catch { ...}
return response;
}
}
here, based on the displayname parameter, I can decide which NamedClient is to be used.
Is there any other efficient way to achieve required functionality? Can I use TypedClient instead?
asp.net-core-2.1 .net-core-2.1 httpclientfactory
asp.net-core-2.1 .net-core-2.1 httpclientfactory
asked Nov 14 '18 at 14:40
PriyaPriya
61161231
61161231
Can I use Single TypedClient with multiple different Base Urls?
– Priya
Nov 14 '18 at 14:59
add a comment |
Can I use Single TypedClient with multiple different Base Urls?
– Priya
Nov 14 '18 at 14:59
Can I use Single TypedClient with multiple different Base Urls?
– Priya
Nov 14 '18 at 14:59
Can I use Single TypedClient with multiple different Base Urls?
– Priya
Nov 14 '18 at 14:59
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53302742%2fhttpclientfactory-with-dynamic-configurations%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53302742%2fhttpclientfactory-with-dynamic-configurations%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Can I use Single TypedClient with multiple different Base Urls?
– Priya
Nov 14 '18 at 14:59