public async Task Invoke(HttpContext httpContext) { try { if (IsGrpcGatewayRequest(httpContext)) { if (!IsAllowedMethod(httpContext)) { httpContext.Response.Clear(); httpContext.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; return; } string body; using (var sr = new StreamReader(httpContext.Request.Body, Encoding.UTF8)) body = sr.ReadToEnd(); if (string.IsNullOrWhiteSpace(body)) { body = "[]"; } var lastIndexOf = httpContext.Request.Path.Value.LastIndexOf('/') + 1; var key = new StringSegment(httpContext.Request.Path.Value, lastIndexOf, httpContext.Request.Path.Value.Length - lastIndexOf); var metadata = new Metadata(); foreach (var header in httpContext.Request.Headers) { metadata.Add(header.Key, header.Value); } var client = new CacheServiceClient(_channel); object response; if (HttpMethods.IsGet(httpContext.Request.Method)) { response = await client.GetAsync(new GetRequest { Key = key.ToString() }, new CallOptions().WithHeaders(metadata)); } else { response = await client.SetAsync(JsonConvert.DeserializeObject <SetRequest>(body), new CallOptions().WithHeaders(metadata)); } var responseBody = JsonConvert.SerializeObject(response, new[] { new Newtonsoft.Json.Converters.StringEnumConverter() }); httpContext.Response.ContentType = "application/json"; await httpContext.Response.WriteAsync(responseBody); return; } else { await _next(httpContext); } } catch (Exception ex) { httpContext.Response.StatusCode = 500; await httpContext.Response.WriteAsync(ex.ToString()); } }
private static async Task GeneratedClientExample(CallInvoker invoker) { var client = new CacheServiceClient(invoker); try { await client.SetAsync(new SetRequest { Key = "ClientDemo", Value = ByteString.CopyFrom("ClientDemo", Encoding.UTF8) }, options : new CallOptions().WithDeadline(DateTime.UtcNow.AddSeconds(2))); var response = await client.GetAsync(new GetRequest { Key = "ClientDemo", }, options : new CallOptions().WithDeadline(DateTime.UtcNow.AddSeconds(2))); Logger.Info("Get by key pattern 'Client'"); using (var stream = client.GetByKeyPattern(new GetByKeyPatternRequest { Pattern = "Client", }, options: new CallOptions().WithDeadline(DateTime.UtcNow.AddSeconds(5)))) { while (await stream.ResponseStream.MoveNext()) { var current = stream.ResponseStream.Current; Logger.Info($"Got key '{current.Key}' with value '{current.Value.ToStringUtf8()}'"); } }; } catch (RpcException ex) { Logger.Error(ex, "Error setting key: 'ClientDemo'"); } }