Browse Source

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

features/migration-dotnet3
ericuss 5 years ago
parent
commit
9b1c690c9e
5 changed files with 93 additions and 123 deletions
  1. +16
    -3
      src/Clients/Clients.Grpc.Caller/Program.cs
  2. +3
    -3
      src/Services/Basket/Basket.API/Basket.API.csproj
  3. +31
    -53
      src/Services/Basket/Basket.API/Grpc/BasketService.cs
  4. +2
    -0
      src/Services/Basket/Basket.API/Proto/basket.proto
  5. +41
    -64
      src/Services/Basket/Basket.API/Startup.cs

+ 16
- 3
src/Clients/Clients.Grpc.Caller/Program.cs View File

@ -1,6 +1,7 @@
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
using GrpcBasket;
namespace Clients.Grpc.Caller
@ -25,9 +26,21 @@ namespace Clients.Grpc.Caller
httpClient.BaseAddress = new Uri("http://localhost:5580");
//httpClient.DefaultRequestVersion = Version.Parse("2.0");
var client = GrpcClient.Create<Basket.BasketClient>(httpClient);
var reply = await client.GetBasketByIdAsync(
new BasketRequest { Id = "11" });
Console.WriteLine("Greeting: " + reply.Buyerid);
try
{
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.ReadKey();
}


+ 3
- 3
src/Services/Basket/Basket.API/Basket.API.csproj View File

@ -27,11 +27,11 @@
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="$(Microsoft_ApplicationInsights_AspNetCore)" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="$(Microsoft_ApplicationInsights_DependencyCollector)" />
<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.HealthChecks" Version="$(Microsoft_AspNetCore_HealthChecks)" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.0.0-preview8.19405.4" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" 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="$(Microsoft_Extensions_Logging_AzureAppServices)" />
<PackageReference Include="Serilog.AspNetCore" Version="$(Serilog_AspNetCore)" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="$(Serilog_Enrichers_Environment)" />
<PackageReference Include="Serilog.Settings.Configuration" Version="$(Serilog_Settings_Configuration)" />


+ 31
- 53
src/Services/Basket/Basket.API/Grpc/BasketService.cs View File

@ -20,46 +20,24 @@ namespace GrpcBasket
}
[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}");
//context.ResponseTrailers.Add("grpc-status", "0");
//context.Status = Status.DefaultSuccess;
var data = await _repository.GetBasketAsync(request.Id);
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())
// {
// 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();
return new CustomerBasketResponse();
}
public override async Task<CustomerBasketResponse> UpdateBasket(CustomerBasketRequest request, ServerCallContext context)
@ -87,16 +65,16 @@ namespace GrpcBasket
Buyerid = customerBasket.BuyerId
};
// customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse
// {
// Id = item.Id,
// Oldunitprice = (double)item.OldUnitPrice,
// Pictureurl = item.PictureUrl,
// Productid = item.ProductId,
// Productname = item.ProductName,
// Quantity = item.Quantity,
// Unitprice = (double)item.UnitPrice
// }));
customerBasket.Items.ForEach(item => response.Items.Add(new BasketItemResponse
{
Id = item.Id,
Oldunitprice = (double)item.OldUnitPrice,
Pictureurl = item.PictureUrl,
Productid = item.ProductId,
Productname = item.ProductName,
Quantity = item.Quantity,
Unitprice = (double)item.UnitPrice
}));
return response;
}
@ -108,16 +86,16 @@ namespace GrpcBasket
BuyerId = customerBasketRequest.Buyerid
};
// customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem
// {
// Id = item.Id,
// OldUnitPrice = (decimal)item.Oldunitprice,
// PictureUrl = item.Pictureurl,
// ProductId = item.Productid,
// ProductName = item.Productname,
// Quantity = item.Quantity,
// UnitPrice = (decimal)item.Unitprice
// }));
customerBasketRequest.Items.ToList().ForEach(item => response.Items.Add(new BasketItem
{
Id = item.Id,
OldUnitPrice = (decimal)item.Oldunitprice,
PictureUrl = item.Pictureurl,
ProductId = item.Productid,
ProductName = item.Productname,
Quantity = item.Quantity,
UnitPrice = (decimal)item.Unitprice
}));
return response;
}


+ 2
- 0
src/Services/Basket/Basket.API/Proto/basket.proto View File

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


+ 41
- 64
src/Services/Basket/Basket.API/Startup.cs View File

@ -200,41 +200,18 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
app.UsePathBase(pathBase);
}
//app.Use((context, next) =>
//{
// Log.Logger.Information("Custom middleware to avoid trailers");
// Log.Logger.Information("Custom middleware context.Response {@context.Response}", context.Response);
// Log.Logger.Information("Custom middleware context.Response.SupportsTrailers {context.Response.SupportsTrailers}", context.Response.SupportsTrailers());
// 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.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();
// ConfigureAuth(app);
ConfigureAuth(app);
// app.UseStaticFiles();
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
@ -242,20 +219,20 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
endpoints.MapGrpcService<BasketService>();
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
// endpoints.MapGet("/_proto/", async ctx =>
// {
// ctx.Response.ContentType = "text/plain";
// using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
// using var sr = new StreamReader(fs);
// while (!sr.EndOfStream)
// {
// var line = await sr.ReadLineAsync();
// if (line != "/* >>" || line != "<< */")
// {
// await ctx.Response.WriteAsync(line);
// }
// }
// });
endpoints.MapGet("/_proto/", async ctx =>
{
ctx.Response.ContentType = "text/plain";
using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
using var sr = new StreamReader(fs);
while (!sr.EndOfStream)
{
var line = await sr.ReadLineAsync();
if (line != "/* >>" || line != "<< */")
{
await ctx.Response.WriteAsync(line);
}
}
});
endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
{
Predicate = _ => true,
@ -278,22 +255,22 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
private void ConfigureAuthService(IServiceCollection services)
{
// prevent from mapping "sub" claim to nameidentifier.
// JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
// var identityUrl = Configuration.GetValue<string>("IdentityUrl");
// services.AddAuthentication(options =>
// {
// options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
// options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
// }).AddJwtBearer(options =>
// {
// options.Authority = identityUrl;
// options.RequireHttpsMetadata = false;
// options.Audience = "basket";
// });
// prevent from mapping "sub" claim to nameidentifier.
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
var identityUrl = Configuration.GetValue<string>("IdentityUrl");
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.Audience = "basket";
});
}
protected virtual void ConfigureAuth(IApplicationBuilder app)
@ -303,8 +280,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
app.UseMiddleware<ByPassAuthMiddleware>();
}
// app.UseAuthentication();
// app.UseAuthorization();
app.UseAuthentication();
app.UseAuthorization();
}
private void RegisterEventBus(IServiceCollection services)


Loading…
Cancel
Save