restore options and grpc calling from console app it's working

This commit is contained in:
ericuss 2019-08-26 14:52:57 +02:00
parent e58429ac2a
commit 9b1c690c9e
5 changed files with 90 additions and 120 deletions

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client; using Grpc.Net.Client;
using GrpcBasket; using GrpcBasket;
namespace Clients.Grpc.Caller namespace Clients.Grpc.Caller
@ -25,9 +26,21 @@ namespace Clients.Grpc.Caller
httpClient.BaseAddress = new Uri("http://localhost:5580"); httpClient.BaseAddress = new Uri("http://localhost:5580");
//httpClient.DefaultRequestVersion = Version.Parse("2.0"); //httpClient.DefaultRequestVersion = Version.Parse("2.0");
var client = GrpcClient.Create<Basket.BasketClient>(httpClient); var client = GrpcClient.Create<Basket.BasketClient>(httpClient);
var reply = await client.GetBasketByIdAsync(
new BasketRequest { Id = "11" }); try
Console.WriteLine("Greeting: " + reply.Buyerid); {
var reply = await client.GetBasketByIdAsync(
new BasketRequest { Id = "4f71a02f-4738-43a9-8c81-7652877e7102" });
Console.WriteLine("Greeting: " + reply.Buyerid);
Console.WriteLine("Greeting: " + reply.Items);
}
//catch(Grpc)
catch (RpcException e)
{
Console.WriteLine($"Error calling via grpc: {e.Status} - {e.Message}");
}
Console.WriteLine("Press any key to exit..."); Console.WriteLine("Press any key to exit...");
Console.ReadKey(); Console.ReadKey();
} }

View File

@ -27,11 +27,11 @@
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="$(Microsoft_ApplicationInsights_AspNetCore)" /> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="$(Microsoft_ApplicationInsights_AspNetCore)" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="$(Microsoft_ApplicationInsights_DependencyCollector)" /> <PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="$(Microsoft_ApplicationInsights_DependencyCollector)" />
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="$(Microsoft_ApplicationInsights_Kubernetes)" /> <PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="$(Microsoft_ApplicationInsights_Kubernetes)" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0-preview8.19405.7" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="$(Microsoft_AspNetCore_Authentication_JwtBearer)" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="$(Microsoft_AspNetCore_Diagnostics_HealthChecks)" /> <PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="$(Microsoft_AspNetCore_Diagnostics_HealthChecks)" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="$(Microsoft_AspNetCore_HealthChecks)" /> <PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="$(Microsoft_AspNetCore_HealthChecks)" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.0.0-preview8.19405.4" /> <PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="$(Microsoft_Extensions_Configuration_AzureKeyVault)" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="3.0.0-preview8.19405.4" /> <PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="$(Microsoft_Extensions_Logging_AzureAppServices)" />
<PackageReference Include="Serilog.AspNetCore" Version="$(Serilog_AspNetCore)" /> <PackageReference Include="Serilog.AspNetCore" Version="$(Serilog_AspNetCore)" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="$(Serilog_Enrichers_Environment)" /> <PackageReference Include="Serilog.Enrichers.Environment" Version="$(Serilog_Enrichers_Environment)" />
<PackageReference Include="Serilog.Settings.Configuration" Version="$(Serilog_Settings_Configuration)" /> <PackageReference Include="Serilog.Settings.Configuration" Version="$(Serilog_Settings_Configuration)" />

View File

@ -20,46 +20,24 @@ namespace GrpcBasket
} }
[AllowAnonymous] [AllowAnonymous]
public override Task<CustomerBasketResponse> GetBasketById(BasketRequest request, ServerCallContext context) public override async Task<CustomerBasketResponse> GetBasketById(BasketRequest request, ServerCallContext context)
{ {
_logger.LogInformation($"Begin grpc call from method {context.Method} for basket id {request.Id}"); _logger.LogInformation($"Begin grpc call from method {context.Method} for basket id {request.Id}");
//context.ResponseTrailers.Add("grpc-status", "0"); var data = await _repository.GetBasketAsync(request.Id);
//context.Status = Status.DefaultSuccess;
return Task.FromResult(new CustomerBasketResponse if (data != null)
{ {
Buyerid = "55" context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist");
});
return MapToCustomerBasketResponse(data);
}
else
{
context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist");
}
// if (!context.Response.SupportsTrailers()) return new CustomerBasketResponse();
// {
// var headers = new HeaderDictionary();
// headers.Add("grpc-status", "0");
// Log.Logger.Information("Custom middleware headers {@headers}", headers);
// context.Features.Set<IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
// {
// Trailers = headers
// });
// }
// return next();
// var data = await _repository.GetBasketAsync(request.Id);
// if (data != null)
// {
// context.Status = new Status(StatusCode.OK, $"Basket with id {request.Id} do exist");
// return MapToCustomerBasketResponse(data);
// }
// else
// {
// context.Status = new Status(StatusCode.NotFound, $"Basket with id {request.Id} do not exist");
// }
// return new CustomerBasketResponse();
} }
public override async Task<CustomerBasketResponse> UpdateBasket(CustomerBasketRequest request, ServerCallContext context) public override async Task<CustomerBasketResponse> UpdateBasket(CustomerBasketRequest request, ServerCallContext context)
@ -87,16 +65,16 @@ namespace GrpcBasket
Buyerid = customerBasket.BuyerId Buyerid = customerBasket.BuyerId
}; };
// customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse
// { {
// Id = item.Id, Id = item.Id,
// Oldunitprice = (double)item.OldUnitPrice, Oldunitprice = (double)item.OldUnitPrice,
// Pictureurl = item.PictureUrl, Pictureurl = item.PictureUrl,
// Productid = item.ProductId, Productid = item.ProductId,
// Productname = item.ProductName, Productname = item.ProductName,
// Quantity = item.Quantity, Quantity = item.Quantity,
// Unitprice = (double)item.UnitPrice Unitprice = (double)item.UnitPrice
// })); }));
return response; return response;
} }
@ -108,16 +86,16 @@ namespace GrpcBasket
BuyerId = customerBasketRequest.Buyerid BuyerId = customerBasketRequest.Buyerid
}; };
// customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem
// { {
// Id = item.Id, Id = item.Id,
// OldUnitPrice = (decimal)item.Oldunitprice, OldUnitPrice = (decimal)item.Oldunitprice,
// PictureUrl = item.Pictureurl, PictureUrl = item.Pictureurl,
// ProductId = item.Productid, ProductId = item.Productid,
// ProductName = item.Productname, ProductName = item.Productname,
// Quantity = item.Quantity, Quantity = item.Quantity,
// UnitPrice = (decimal)item.Unitprice UnitPrice = (decimal)item.Unitprice
// })); }));
return response; return response;
} }

View File

@ -15,10 +15,12 @@ message BasketRequest {
message CustomerBasketRequest { message CustomerBasketRequest {
string buyerid = 1; string buyerid = 1;
repeated BasketItemResponse items = 2;
} }
message CustomerBasketResponse { message CustomerBasketResponse {
string buyerid = 1; string buyerid = 1;
repeated BasketItemResponse items = 2;
} }
message BasketItemResponse { message BasketItemResponse {

View File

@ -200,41 +200,18 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
app.UsePathBase(pathBase); app.UsePathBase(pathBase);
} }
app.UseSwagger()
//app.Use((context, next) => .UseSwaggerUI(setup =>
//{ {
// Log.Logger.Information("Custom middleware to avoid trailers"); setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1");
// Log.Logger.Information("Custom middleware context.Response {@context.Response}", context.Response); setup.OAuthClientId("basketswaggerui");
// Log.Logger.Information("Custom middleware context.Response.SupportsTrailers {context.Response.SupportsTrailers}", context.Response.SupportsTrailers()); setup.OAuthAppName("Basket Swagger UI");
// if (!context.Response.SupportsTrailers()) });
// {
// var headers = new HeaderDictionary();
// headers.Add("grpc-status", "0");
// Log.Logger.Information("Custom middleware headers {@headers}", headers);
// context.Features.Set<IHttpResponseTrailersFeature>(new TestHttpResponseTrailersFeature
// {
// Trailers = headers
// });
// }
// return next();
//});
//app.UseSwagger()
// .UseSwaggerUI(setup =>
// {
// setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1");
// setup.OAuthClientId("basketswaggerui");
// setup.OAuthAppName("Basket Swagger UI");
// });
app.UseRouting(); app.UseRouting();
// ConfigureAuth(app); ConfigureAuth(app);
// app.UseStaticFiles(); app.UseStaticFiles();
app.UseCors("CorsPolicy"); app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
@ -242,20 +219,20 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
endpoints.MapGrpcService<BasketService>(); endpoints.MapGrpcService<BasketService>();
endpoints.MapDefaultControllerRoute(); endpoints.MapDefaultControllerRoute();
endpoints.MapControllers(); endpoints.MapControllers();
// endpoints.MapGet("/_proto/", async ctx => endpoints.MapGet("/_proto/", async ctx =>
// { {
// ctx.Response.ContentType = "text/plain"; ctx.Response.ContentType = "text/plain";
// using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read); using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
// using var sr = new StreamReader(fs); using var sr = new StreamReader(fs);
// while (!sr.EndOfStream) while (!sr.EndOfStream)
// { {
// var line = await sr.ReadLineAsync(); var line = await sr.ReadLineAsync();
// if (line != "/* >>" || line != "<< */") if (line != "/* >>" || line != "<< */")
// { {
// await ctx.Response.WriteAsync(line); await ctx.Response.WriteAsync(line);
// } }
// } }
// }); });
endpoints.MapHealthChecks("/hc", new HealthCheckOptions() endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
{ {
Predicate = _ => true, Predicate = _ => true,
@ -278,22 +255,22 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
private void ConfigureAuthService(IServiceCollection services) private void ConfigureAuthService(IServiceCollection services)
{ {
// prevent from mapping "sub" claim to nameidentifier. // prevent from mapping "sub" claim to nameidentifier.
// JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
// var identityUrl = Configuration.GetValue<string>("IdentityUrl"); var identityUrl = Configuration.GetValue<string>("IdentityUrl");
// services.AddAuthentication(options => services.AddAuthentication(options =>
// { {
// options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
// options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
// }).AddJwtBearer(options => }).AddJwtBearer(options =>
// { {
// options.Authority = identityUrl; options.Authority = identityUrl;
// options.RequireHttpsMetadata = false; options.RequireHttpsMetadata = false;
// options.Audience = "basket"; options.Audience = "basket";
// }); });
} }
protected virtual void ConfigureAuth(IApplicationBuilder app) protected virtual void ConfigureAuth(IApplicationBuilder app)
@ -303,8 +280,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
app.UseMiddleware<ByPassAuthMiddleware>(); app.UseMiddleware<ByPassAuthMiddleware>();
} }
// app.UseAuthentication(); app.UseAuthentication();
// app.UseAuthorization(); app.UseAuthorization();
} }
private void RegisterEventBus(IServiceCollection services) private void RegisterEventBus(IServiceCollection services)