Skip to content

Commit 96816e7

Browse files
committed
Refactor aggregators to use AddHttpClient like on WebMVC
1 parent 554b4e4 commit 96816e7

12 files changed

Lines changed: 356 additions & 203 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using Microsoft.AspNetCore.Authentication;
2+
using Microsoft.AspNetCore.Http;
3+
using System.Collections.Generic;
4+
using System.Net.Http;
5+
using System.Net.Http.Headers;
6+
using System.Threading;
7+
using System.Threading.Tasks;
8+
9+
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure
10+
{
11+
public class HttpClientAuthorizationDelegatingHandler
12+
: DelegatingHandler
13+
{
14+
private readonly IHttpContextAccessor _httpContextAccesor;
15+
16+
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccesor)
17+
{
18+
_httpContextAccesor = httpContextAccesor;
19+
}
20+
21+
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
22+
{
23+
var authorizationHeader = _httpContextAccesor.HttpContext
24+
.Request.Headers["Authorization"];
25+
26+
if (!string.IsNullOrEmpty(authorizationHeader))
27+
{
28+
request.Headers.Add("Authorization", new List<string>() { authorizationHeader });
29+
}
30+
31+
var token = await GetToken();
32+
33+
if (token != null)
34+
{
35+
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
36+
}
37+
38+
return await base.SendAsync(request, cancellationToken);
39+
}
40+
41+
async Task<string> GetToken()
42+
{
43+
const string ACCESS_TOKEN = "access_token";
44+
45+
return await _httpContextAccesor.HttpContext
46+
.GetTokenAsync(ACCESS_TOKEN);
47+
}
48+
}
49+
}

src/ApiGateways/Mobile.Bff.Shopping/aggregator/Mobile.Shopping.HttpAggregator.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<ItemGroup>
1515
<PackageReference Include="Microsoft.AspNetCore.App" />
1616
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.1.0" />
17+
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="2.1.0-rc1-final" />
1718
</ItemGroup>
1819

1920
<ItemGroup>
Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,41 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.AspNetCore.Authentication;
6-
using Microsoft.AspNetCore.Http;
7-
using Microsoft.eShopOnContainers.BuildingBlocks.Resilience.Http;
1+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
2+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
83
using Microsoft.Extensions.Logging;
94
using Microsoft.Extensions.Options;
105
using Newtonsoft.Json;
11-
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
12-
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
6+
using System.Net.Http;
7+
using System.Threading.Tasks;
138

149
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
1510
{
1611
public class BasketService : IBasketService
1712
{
1813

19-
private readonly IHttpClient _apiClient;
14+
private readonly HttpClient _httpClient;
2015
private readonly ILogger<BasketService> _logger;
2116
private readonly UrlsConfig _urls;
22-
private readonly IHttpContextAccessor _httpContextAccessor;
2317

24-
public BasketService(IHttpClient httpClient, IHttpContextAccessor httpContextAccessor, ILogger<BasketService> logger, IOptionsSnapshot<UrlsConfig> config)
18+
public BasketService(HttpClient httpClient, ILogger<BasketService> logger, IOptions<UrlsConfig> config)
2519
{
26-
_apiClient = httpClient;
20+
_httpClient = httpClient;
2721
_logger = logger;
2822
_urls = config.Value;
29-
_httpContextAccessor = httpContextAccessor;
3023
}
3124

3225
public async Task<BasketData> GetById(string id)
3326
{
34-
var token = await GetUserTokenAsync();
35-
var data = await _apiClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id), token);
27+
var data = await _httpClient.GetStringAsync(_urls.Basket + UrlsConfig.BasketOperations.GetItemById(id));
28+
3629
var basket = !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject<BasketData>(data) : null;
30+
3731
return basket;
3832
}
3933

4034
public async Task Update(BasketData currentBasket)
4135
{
42-
var token = await GetUserTokenAsync();
43-
var data = await _apiClient.PostAsync<BasketData>(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket(), currentBasket, token);
44-
int i = 0;
45-
}
36+
var basketContent = new StringContent(JsonConvert.SerializeObject(currentBasket), System.Text.Encoding.UTF8, "application/json");
4637

47-
async Task<string> GetUserTokenAsync()
48-
{
49-
var context = _httpContextAccessor.HttpContext;
50-
return await context.GetTokenAsync("access_token");
38+
var data = await _httpClient.PostAsync(_urls.Basket + UrlsConfig.BasketOperations.UpdateBasket(), basketContent);
5139
}
5240
}
5341
}
Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,41 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.eShopOnContainers.BuildingBlocks.Resilience.Http;
1+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
2+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
63
using Microsoft.Extensions.Logging;
74
using Microsoft.Extensions.Options;
85
using Newtonsoft.Json;
9-
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
10-
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
6+
using System.Collections.Generic;
7+
using System.Net.Http;
8+
using System.Threading.Tasks;
119

1210
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
1311
{
1412
public class CatalogService : ICatalogService
1513
{
16-
17-
private readonly IHttpClient _apiClient;
14+
private readonly HttpClient _httpClient;
1815
private readonly ILogger<CatalogService> _logger;
1916
private readonly UrlsConfig _urls;
2017

21-
public CatalogService(IHttpClient httpClient, ILogger<CatalogService> logger, IOptionsSnapshot<UrlsConfig> config)
18+
public CatalogService(HttpClient httpClient, ILogger<CatalogService> logger, IOptions<UrlsConfig> config)
2219
{
23-
_apiClient = httpClient;
20+
_httpClient = httpClient;
2421
_logger = logger;
2522
_urls = config.Value;
2623
}
2724

2825
public async Task<CatalogItem> GetCatalogItem(int id)
2926
{
30-
var data = await _apiClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id));
31-
var item = JsonConvert.DeserializeObject<CatalogItem>(data);
32-
return item;
27+
var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemById(id));
28+
var catalogItem = JsonConvert.DeserializeObject<CatalogItem>(stringContent);
29+
30+
return catalogItem;
3331
}
3432

3533
public async Task<IEnumerable<CatalogItem>> GetCatalogItems(IEnumerable<int> ids)
3634
{
37-
var data = await _apiClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids));
38-
var item = JsonConvert.DeserializeObject<CatalogItem[]>(data);
39-
return item;
35+
var stringContent = await _httpClient.GetStringAsync(_urls.Catalog + UrlsConfig.CatalogOperations.GetItemsById(ids));
36+
var catalogItems = JsonConvert.DeserializeObject<CatalogItem[]>(stringContent);
4037

38+
return catalogItems;
4139
}
4240
}
4341
}
Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Threading.Tasks;
5-
using Microsoft.eShopOnContainers.BuildingBlocks.Resilience.Http;
1+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
2+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
63
using Microsoft.Extensions.Logging;
74
using Microsoft.Extensions.Options;
85
using Newtonsoft.Json;
9-
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Config;
10-
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
6+
using System.Net.Http;
7+
using System.Threading.Tasks;
118

129
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
1310
{
1411
public class OrderApiClient : IOrderApiClient
1512
{
16-
17-
private readonly IHttpClient _apiClient;
13+
private readonly HttpClient _apiClient;
1814
private readonly ILogger<OrderApiClient> _logger;
1915
private readonly UrlsConfig _urls;
2016

21-
public OrderApiClient(IHttpClient httpClient, ILogger<OrderApiClient> logger, IOptionsSnapshot<UrlsConfig> config)
17+
public OrderApiClient(HttpClient httpClient, ILogger<OrderApiClient> logger, IOptions<UrlsConfig> config)
2218
{
2319
_apiClient = httpClient;
2420
_logger = logger;
@@ -27,11 +23,15 @@ public OrderApiClient(IHttpClient httpClient, ILogger<OrderApiClient> logger, IO
2723

2824
public async Task<OrderData> GetOrderDraftFromBasket(BasketData basket)
2925
{
30-
var url = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft();
31-
var response = await _apiClient.PostAsync<BasketData>(url, basket);
26+
var uri = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft();
27+
var content = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
28+
var response = await _apiClient.PostAsync(uri, content);
29+
3230
response.EnsureSuccessStatusCode();
33-
var jsonResponse = await response.Content.ReadAsStringAsync();
34-
return JsonConvert.DeserializeObject<OrderData>(jsonResponse);
31+
32+
var ordersDraftResponse = await response.Content.ReadAsStringAsync();
33+
34+
return JsonConvert.DeserializeObject<OrderData>(ordersDraftResponse);
3535
}
3636
}
3737
}

src/ApiGateways/Mobile.Bff.Shopping/aggregator/Startup.cs

Lines changed: 73 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Filters.Basket.API.Infrastructure.Filters;
1717
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services;
1818
using Swashbuckle.AspNetCore.Swagger;
19+
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Infrastructure;
20+
using Polly.Extensions.Http;
21+
using Polly;
1922

2023
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator
2124
{
@@ -31,14 +34,47 @@ public Startup(IConfiguration configuration)
3134
// This method gets called by the runtime. Use this method to add services to the container.
3235
public void ConfigureServices(IServiceCollection services)
3336
{
34-
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
35-
services.AddSingleton<IHttpClient, StandardHttpClient>();
36-
services.AddTransient<ICatalogService, CatalogService>();
37-
services.AddTransient<IBasketService, BasketService>();
38-
services.AddTransient<IOrderApiClient, OrderApiClient>();
37+
services.AddCustomMvc(Configuration)
38+
.AddCustomAuthentication(Configuration)
39+
.AddHttpServices();
40+
}
41+
42+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
43+
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
44+
{
45+
var pathBase = Configuration["PATH_BASE"];
46+
47+
if (!string.IsNullOrEmpty(pathBase))
48+
{
49+
loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
50+
app.UsePathBase(pathBase);
51+
}
52+
53+
app.UseCors("CorsPolicy");
54+
55+
if (env.IsDevelopment())
56+
{
57+
app.UseDeveloperExceptionPage();
58+
}
59+
60+
app.UseAuthentication();
61+
62+
app.UseMvc();
63+
64+
app.UseSwagger().UseSwaggerUI(c =>
65+
{
66+
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1");
67+
c.ConfigureOAuth2("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI");
68+
});
69+
}
70+
}
3971

72+
public static class ServiceCollectionExtensions
73+
{
74+
public static IServiceCollection AddCustomMvc(this IServiceCollection services, IConfiguration configuration)
75+
{
4076
services.AddOptions();
41-
services.Configure<UrlsConfig>(Configuration.GetSection("urls"));
77+
services.Configure<UrlsConfig>(configuration.GetSection("urls"));
4278

4379
services.AddMvc();
4480

@@ -57,8 +93,8 @@ public void ConfigureServices(IServiceCollection services)
5793
{
5894
Type = "oauth2",
5995
Flow = "implicit",
60-
AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
61-
TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
96+
AuthorizationUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
97+
TokenUrl = $"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
6298
Scopes = new Dictionary<string, string>()
6399
{
64100
{ "mobileshoppingagg", "Shopping Aggregator for Mobile Clients" }
@@ -77,9 +113,12 @@ public void ConfigureServices(IServiceCollection services)
77113
.AllowCredentials());
78114
});
79115

80-
116+
return services;
117+
}
118+
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration)
119+
{
81120
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
82-
var identityUrl = Configuration.GetValue<string>("urls:identity");
121+
var identityUrl = configuration.GetValue<string>("urls:identity");
83122
services.AddAuthentication(options =>
84123
{
85124
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
@@ -102,37 +141,40 @@ public void ConfigureServices(IServiceCollection services)
102141
}
103142
};
104143
});
105-
}
106144

107-
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
108-
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
145+
return services;
146+
}
147+
public static IServiceCollection AddHttpServices(this IServiceCollection services)
109148
{
149+
//register delegating handlers
150+
services.AddTransient<HttpClientAuthorizationDelegatingHandler>();
151+
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
110152

111-
var pathBase = Configuration["PATH_BASE"];
112-
if (!string.IsNullOrEmpty(pathBase))
113-
{
114-
loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
115-
app.UsePathBase(pathBase);
116-
}
153+
//register http services
154+
var retriesWithExponentialBackoff = HttpPolicyExtensions
155+
.HandleTransientHttpError()
156+
.WaitAndRetryAsync(7, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
117157

118-
app.UseCors("CorsPolicy");
158+
var circuitBreaker = HttpPolicyExtensions
159+
.HandleTransientHttpError()
160+
.CircuitBreakerAsync(6, TimeSpan.FromSeconds(30));
119161

120-
if (env.IsDevelopment())
121-
{
122-
app.UseDeveloperExceptionPage();
123-
}
162+
services.AddHttpClient<IBasketService, BasketService>()
163+
.AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>()
164+
.AddPolicyHandler(retriesWithExponentialBackoff)
165+
.AddPolicyHandler(circuitBreaker);
124166

125-
app.UseAuthentication();
167+
services.AddHttpClient<ICatalogService, CatalogService>()
168+
.AddPolicyHandler(retriesWithExponentialBackoff)
169+
.AddPolicyHandler(circuitBreaker);
126170

127-
app.UseMvc();
171+
services.AddHttpClient<IOrderApiClient, OrderApiClient>()
172+
.AddPolicyHandler(retriesWithExponentialBackoff)
173+
.AddPolicyHandler(circuitBreaker);
128174

129-
app.UseSwagger().UseSwaggerUI(c =>
130-
{
131-
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Purchase BFF V1");
132-
c.ConfigureOAuth2("Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregatorwaggerui", "", "", "Purchase BFF Swagger UI");
133-
});
134175

135176

177+
return services;
136178
}
137179
}
138180
}

0 commit comments

Comments
 (0)