Skip to content

Commit 9b1c690

Browse files
author
ericuss
committed
restore options and grpc calling from console app it's working
1 parent e58429a commit 9b1c690

5 files changed

Lines changed: 93 additions & 123 deletions

File tree

src/Clients/Clients.Grpc.Caller/Program.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Net.Http;
33
using System.Threading.Tasks;
4+
using Grpc.Core;
45
using Grpc.Net.Client;
56
using GrpcBasket;
67
namespace Clients.Grpc.Caller
@@ -25,9 +26,21 @@ static async Task Main(string[] args)
2526
httpClient.BaseAddress = new Uri("http://localhost:5580");
2627
//httpClient.DefaultRequestVersion = Version.Parse("2.0");
2728
var client = GrpcClient.Create<Basket.BasketClient>(httpClient);
28-
var reply = await client.GetBasketByIdAsync(
29-
new BasketRequest { Id = "11" });
30-
Console.WriteLine("Greeting: " + reply.Buyerid);
29+
30+
try
31+
{
32+
var reply = await client.GetBasketByIdAsync(
33+
new BasketRequest { Id = "4f71a02f-4738-43a9-8c81-7652877e7102" });
34+
Console.WriteLine("Greeting: " + reply.Buyerid);
35+
Console.WriteLine("Greeting: " + reply.Items);
36+
37+
}
38+
//catch(Grpc)
39+
catch (RpcException e)
40+
{
41+
Console.WriteLine($"Error calling via grpc: {e.Status} - {e.Message}");
42+
}
43+
3144
Console.WriteLine("Press any key to exit...");
3245
Console.ReadKey();
3346
}

src/Services/Basket/Basket.API/Basket.API.csproj

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@
2727
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="$(Microsoft_ApplicationInsights_AspNetCore)" />
2828
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="$(Microsoft_ApplicationInsights_DependencyCollector)" />
2929
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="$(Microsoft_ApplicationInsights_Kubernetes)" />
30-
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0-preview8.19405.7" />
30+
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="$(Microsoft_AspNetCore_Authentication_JwtBearer)" />
3131
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="$(Microsoft_AspNetCore_Diagnostics_HealthChecks)" />
3232
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="$(Microsoft_AspNetCore_HealthChecks)" />
33-
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.0.0-preview8.19405.4" />
34-
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="3.0.0-preview8.19405.4" />
33+
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="$(Microsoft_Extensions_Configuration_AzureKeyVault)" />
34+
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="$(Microsoft_Extensions_Logging_AzureAppServices)" />
3535
<PackageReference Include="Serilog.AspNetCore" Version="$(Serilog_AspNetCore)" />
3636
<PackageReference Include="Serilog.Enrichers.Environment" Version="$(Serilog_Enrichers_Environment)" />
3737
<PackageReference Include="Serilog.Settings.Configuration" Version="$(Serilog_Settings_Configuration)" />

src/Services/Basket/Basket.API/Grpc/BasketService.cs

Lines changed: 31 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -20,46 +20,24 @@ public BasketService(IBasketRepository repository, ILogger<BasketService> logger
2020
}
2121

2222
[AllowAnonymous]
23-
public override Task<CustomerBasketResponse> GetBasketById(BasketRequest request, ServerCallContext context)
23+
public override async Task<CustomerBasketResponse> GetBasketById(BasketRequest request, ServerCallContext context)
2424
{
2525
_logger.LogInformation($"Begin grpc call from method {context.Method} for basket id {request.Id}");
2626

27-
//context.ResponseTrailers.Add("grpc-status", "0");
28-
//context.Status = Status.DefaultSuccess;
27+
var data = await _repository.GetBasketAsync(request.Id);
2928

30-
return Task.FromResult(new CustomerBasketResponse
29+
if (data != null)
3130
{
32-
Buyerid = "55"
33-
});
31+
context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist");
3432

33+
return MapToCustomerBasketResponse(data);
34+
}
35+
else
36+
{
37+
context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist");
38+
}
3539

36-
// if (!context.Response.SupportsTrailers())
37-
// {
38-
// var headers = new HeaderDictionary();
39-
// headers.Add("grpc-status", "0");
40-
41-
// Log.Logger.Information("Custom middleware headers {@headers}", headers);
42-
// context.Features.Set<IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
43-
// {
44-
// Trailers = headers
45-
// });
46-
// }
47-
48-
// return next();
49-
// var data = await _repository.GetBasketAsync(request.Id);
50-
51-
// if (data != null)
52-
// {
53-
// context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist");
54-
55-
// return MapToCustomerBasketResponse(data);
56-
// }
57-
// else
58-
// {
59-
// context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist");
60-
// }
61-
62-
// return new CustomerBasketResponse();
40+
return new CustomerBasketResponse();
6341
}
6442

6543
public override async Task<CustomerBasketResponse> UpdateBasket(CustomerBasketRequest request, ServerCallContext context)
@@ -87,16 +65,16 @@ private CustomerBasketResponse MapToCustomerBasketResponse(CustomerBasket custom
8765
Buyerid = customerBasket.BuyerId
8866
};
8967

90-
// customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse
91-
// {
92-
// Id = item.Id,
93-
// Oldunitprice = (double)item.OldUnitPrice,
94-
// Pictureurl = item.PictureUrl,
95-
// Productid = item.ProductId,
96-
// Productname = item.ProductName,
97-
// Quantity = item.Quantity,
98-
// Unitprice = (double)item.UnitPrice
99-
// }));
68+
customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse
69+
{
70+
Id = item.Id,
71+
Oldunitprice = (double)item.OldUnitPrice,
72+
Pictureurl = item.PictureUrl,
73+
Productid = item.ProductId,
74+
Productname = item.ProductName,
75+
Quantity = item.Quantity,
76+
Unitprice = (double)item.UnitPrice
77+
}));
10078

10179
return response;
10280
}
@@ -108,16 +86,16 @@ private CustomerBasket MapToCustomerBasket(CustomerBasketRequest customerBasketR
10886
BuyerId = customerBasketRequest.Buyerid
10987
};
11088

111-
// customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem
112-
// {
113-
// Id = item.Id,
114-
// OldUnitPrice = (decimal)item.Oldunitprice,
115-
// PictureUrl = item.Pictureurl,
116-
// ProductId = item.Productid,
117-
// ProductName = item.Productname,
118-
// Quantity = item.Quantity,
119-
// UnitPrice = (decimal)item.Unitprice
120-
// }));
89+
customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem
90+
{
91+
Id = item.Id,
92+
OldUnitPrice = (decimal)item.Oldunitprice,
93+
PictureUrl = item.Pictureurl,
94+
ProductId = item.Productid,
95+
ProductName = item.Productname,
96+
Quantity = item.Quantity,
97+
UnitPrice = (decimal)item.Unitprice
98+
}));
12199

122100
return response;
123101
}

src/Services/Basket/Basket.API/Proto/basket.proto

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ message BasketRequest {
1515

1616
message CustomerBasketRequest {
1717
string buyerid = 1;
18+
repeated BasketItemResponse items = 2;
1819
}
1920

2021
message CustomerBasketResponse {
2122
string buyerid = 1;
23+
repeated BasketItemResponse items = 2;
2224
}
2325

2426
message BasketItemResponse {

src/Services/Basket/Basket.API/Startup.cs

Lines changed: 41 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -200,62 +200,39 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerF
200200
app.UsePathBase(pathBase);
201201
}
202202

203-
204-
//app.Use((context, next) =>
205-
//{
206-
// Log.Logger.Information("Custom middleware to avoid trailers");
207-
// Log.Logger.Information("Custom middleware context.Response {@context.Response}", context.Response);
208-
// Log.Logger.Information("Custom middleware context.Response.SupportsTrailers {context.Response.SupportsTrailers}", context.Response.SupportsTrailers());
209-
// if (!context.Response.SupportsTrailers())
210-
// {
211-
// var headers = new HeaderDictionary();
212-
// headers.Add("grpc-status", "0");
213-
214-
// Log.Logger.Information("Custom middleware headers {@headers}", headers);
215-
// context.Features.Set<IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
216-
// {
217-
// Trailers = headers
218-
// });
219-
// }
220-
221-
// return next();
222-
223-
224-
//});
225-
226-
//app.UseSwagger()
227-
// .UseSwaggerUI(setup =>
228-
// {
229-
// setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1");
230-
// setup.OAuthClientId("basketswaggerui");
231-
// setup.OAuthAppName("Basket Swagger UI");
232-
// });
203+
app.UseSwagger()
204+
.UseSwaggerUI(setup =>
205+
{
206+
setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1");
207+
setup.OAuthClientId("basketswaggerui");
208+
setup.OAuthAppName("Basket Swagger UI");
209+
});
233210

234211
app.UseRouting();
235-
// ConfigureAuth(app);
212+
ConfigureAuth(app);
236213

237-
// app.UseStaticFiles();
214+
app.UseStaticFiles();
238215

239216
app.UseCors("CorsPolicy");
240217
app.UseEndpoints(endpoints =>
241218
{
242219
endpoints.MapGrpcService<BasketService>();
243220
endpoints.MapDefaultControllerRoute();
244221
endpoints.MapControllers();
245-
// endpoints.MapGet("/_proto/", async ctx =>
246-
// {
247-
// ctx.Response.ContentType = "text/plain";
248-
// using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
249-
// using var sr = new StreamReader(fs);
250-
// while (!sr.EndOfStream)
251-
// {
252-
// var line = await sr.ReadLineAsync();
253-
// if (line != "/* >>" || line != "<< */")
254-
// {
255-
// await ctx.Response.WriteAsync(line);
256-
// }
257-
// }
258-
// });
222+
endpoints.MapGet("/_proto/", async ctx =>
223+
{
224+
ctx.Response.ContentType = "text/plain";
225+
using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
226+
using var sr = new StreamReader(fs);
227+
while (!sr.EndOfStream)
228+
{
229+
var line = await sr.ReadLineAsync();
230+
if (line != "/* >>" || line != "<< */")
231+
{
232+
await ctx.Response.WriteAsync(line);
233+
}
234+
}
235+
});
259236
endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
260237
{
261238
Predicate = _ => true,
@@ -278,22 +255,22 @@ private void RegisterAppInsights(IServiceCollection services)
278255

279256
private void ConfigureAuthService(IServiceCollection services)
280257
{
281-
// prevent from mapping "sub" claim to nameidentifier.
282-
// JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
283-
284-
// var identityUrl = Configuration.GetValue<string>("IdentityUrl");
285-
286-
// services.AddAuthentication(options =>
287-
// {
288-
// options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
289-
// options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
290-
291-
// }).AddJwtBearer(options =>
292-
// {
293-
// options.Authority = identityUrl;
294-
// options.RequireHttpsMetadata = false;
295-
// options.Audience = "basket";
296-
// });
258+
// prevent from mapping "sub" claim to nameidentifier.
259+
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
260+
261+
var identityUrl = Configuration.GetValue<string>("IdentityUrl");
262+
263+
services.AddAuthentication(options =>
264+
{
265+
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
266+
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
267+
268+
}).AddJwtBearer(options =>
269+
{
270+
options.Authority = identityUrl;
271+
options.RequireHttpsMetadata = false;
272+
options.Audience = "basket";
273+
});
297274
}
298275

299276
protected virtual void ConfigureAuth(IApplicationBuilder app)
@@ -303,8 +280,8 @@ protected virtual void ConfigureAuth(IApplicationBuilder app)
303280
app.UseMiddleware<ByPassAuthMiddleware>();
304281
}
305282

306-
// app.UseAuthentication();
307-
// app.UseAuthorization();
283+
app.UseAuthentication();
284+
app.UseAuthorization();
308285
}
309286

310287
private void RegisterEventBus(IServiceCollection services)

0 commit comments

Comments
 (0)