Example #1
0
        public async Task ParsingRequestTestsAsync(string request, string expectedResponse)
        {
            var handler = new JsonRpcRequestHandler <TestableRpcService>(new TestableRpcService());

            var response = await handler.HandleAsync(request, CancellationToken.None).ConfigureAwait(false);

            Assert.Equal(expectedResponse, response);
        }
Example #2
0
        public async Task ParsingRequestTestsAsync(string request, string expectedResponse)
        {
            var handler = new JsonRpcRequestHandler(new TesteableRpcService());

            var response = await handler.HandleAsync(request, new CancellationTokenSource());

            Assert.Equal(expectedResponse, response);
        }
Example #3
0
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var handler = new JsonRpcRequestHandler <IJsonRpcService>(Service);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                var context = await GetHttpContextAsync(stoppingToken).ConfigureAwait(false);

                var request  = context.Request;
                var response = context.Response;

                if (request.HttpMethod == "POST")
                {
                    using var reader = new StreamReader(request.InputStream);
                    string body = await reader.ReadToEndAsync().ConfigureAwait(false);

                    var identity = (HttpListenerBasicIdentity)context.User?.Identity;
                    if (!Config.RequiresCredentials || CheckValidCredentials(identity))
                    {
                        var result = await handler.HandleAsync(body, stoppingToken).ConfigureAwait(false);

                        // result is null only when the request is a notification.
                        if (!string.IsNullOrEmpty(result))
                        {
                            response.ContentType = "application/json-rpc";
                            var output = response.OutputStream;
                            var buffer = Encoding.UTF8.GetBytes(result);
                            await output.WriteAsync(buffer.AsMemory(0, buffer.Length), stoppingToken).ConfigureAwait(false);

                            await output.FlushAsync(stoppingToken).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    }
                }
                else
                {
                    response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                }
                response.Close();
            }
            catch (OperationCanceledException)
            {
                break;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
    }