public void Initialize()
    {
        IsJsonRequestContent = JsonRequestHelpers.HasJsonContentType(HttpContext.Request, out var charset);
        RequestEncoding      = JsonRequestHelpers.GetEncodingFromCharset(charset) ?? Encoding.UTF8;

        // HttpContext.Items is publically exposed as ServerCallContext.UserState.
        // Because this is a custom ServerCallContext, HttpContext must be added to UserState so GetHttpContext() continues to work.
        // https://github.com/grpc/grpc-dotnet/blob/7ef184f3c4cd62fbc3cde55e4bb3e16b58258ca1/src/Grpc.AspNetCore.Server/ServerCallContextExtensions.cs#L53-L61
        HttpContext.Items["__HttpContext"] = HttpContext;
    }
Пример #2
0
    public async Task Request_SupportedCharset_Success(string?charset)
    {
        // Arrange
        Task <HelloReply> UnaryMethod(HelloRequest request, ServerCallContext context)
        {
            return(Task.FromResult(new HelloReply {
                Message = $"Hello {request.Name}!"
            }));
        }

        var method = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>(
            UnaryMethod,
            Greeter.Descriptor.FindMethodByName("SayHelloPost"));

        var encoding    = JsonRequestHelpers.GetEncodingFromCharset(charset);
        var contentType = charset != null
            ? "application/json; charset=" + charset
            : "application/json";

        var client = new HttpClient(Fixture.Handler)
        {
            BaseAddress = new Uri("http://localhost")
        };

        var requestMessage = new HelloRequest {
            Name = "test"
        };
        var content = new ByteArrayContent((encoding ?? Encoding.UTF8).GetBytes(requestMessage.ToString()));

        content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);

        // Act
        var response = await client.PostAsync("/v1/greeter", content).DefaultTimeout();

        var responseText = await response.Content.ReadAsStringAsync();

        using var result = JsonDocument.Parse(responseText);

        // Assert
        Assert.Equal("application/json", response.Content.Headers.ContentType !.MediaType);
        Assert.Equal(encoding?.WebName ?? "utf-8", response.Content.Headers.ContentType !.CharSet);
        Assert.Equal("Hello test!", result.RootElement.GetProperty("message").GetString());
    }