Example #1
0
        public async Task Invoke(HttpContext httpContext)
        {
            // serializer may be mutated in JsonRpcRequest.CreateAsync, so we need new instance for every request
            JsonSerializer serializer = JsonSerializer.Create(_options.JsonSerializerSettings);

            try
            {
                using (var scope = _rpcServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    var requestServices = new CompositeServiceProvider(
                        httpContext.RequestServices,
                        scope.ServiceProvider
                        );

                    JsonRpcRequest request;
                    try
                    {
                        request = await JsonRpcRequest.CreateAsync(httpContext, serializer);
                    }
                    catch (Exception ex)
                    {
                        // todo: log
                        if (!httpContext.Response.HasStarted && !httpContext.RequestAborted.IsCancellationRequested)
                        {
                            await SendResponse(httpContext, new JsonRpcResponse(null, JsonRpcError.PARSE_ERROR, errorData : ex.ToString()), serializer);
                        }
                        return;
                    }

                    var rpcContext = new JsonRpcContext(requestServices, _server, request);

                    await _server.ProcessAsync(rpcContext);

                    if (rpcContext.Request.IsNotification)
                    {
                        httpContext.Response.StatusCode = 204;
                    }
                    else
                    {
                        await SendResponse(httpContext, rpcContext.Response, serializer);
                    }
                }
            }
            catch (Exception ex)
            {
                // todo: log
                if (!httpContext.Response.HasStarted && !httpContext.RequestAborted.IsCancellationRequested)
                {
                    await SendResponse(httpContext, new JsonRpcResponse(null, JsonRpcError.INTERNAL_ERROR, errorData : ex.ToString()), serializer);
                }
            }
        }