Пример #1
0
        private static RpcEndpointOptions BuildOptions(Action <RpcEndpointOptions> configuration)
        {
            var options = new RpcEndpointOptions();

            configuration?.Invoke(options);
            return(options);
        }
Пример #2
0
        /// <summary>
        /// Given successful result, returns Http status code 200 (OK) and uses <see cref="JsonSerializer"/> for serializing the response body.
        /// Otherwise, http status code 404 - NotFound is returned with an empty body.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="jsonOptions">The Json options used for serialization.</param>
        /// <returns>The updated options.</returns>
        public static RpcEndpointOptions UseSystemJsonForOkOrNotFoundResult(this RpcEndpointOptions options, JsonSerializerOptions?jsonOptions = null)
        {
            options.SerializeResponse = async(response, cancellationToken) =>
            {
                var(result, context) = response;

                await(result switch
                {
                    SuccessfullyProcessedRequestResult r => context
                    .WithStatus(HttpStatusCode.OK)
                    .WithContentType(JsonContentType)
                    .Complete(r.Response, jsonOptions, cancellationToken),

                    NotFoundRequestResult r => context
                    .WithStatus(HttpStatusCode.NotFound)
                    .Complete($"{r.RequestName} not found", jsonOptions, cancellationToken),

                    RequestNameRouteValueNotFoundResult r => context
                    .WithStatus(HttpStatusCode.NotFound)
                    .WithContentType(JsonContentType)
                    .Complete(),

                    _ => context
                    .WithStatus(HttpStatusCode.OK)
                    .Complete(result, jsonOptions, cancellationToken)
                });;
            };
        public static IApplicationBuilder UseGrpcService(this IApplicationBuilder app, IConfiguration configuration)
        {
            var option = new RpcEndpointOptions();

            configuration.GetSection("ServiceDiscovery").GetSection("RpcEndpoint").Bind(option);
            app.UseGrpcService(option);
            return(app);
        }
Пример #4
0
        internal static void ValidateOptions(RpcEndpointOptions options)
        {
            AssertHelper.ValidateIsNotNull(options.Path, nameof(options.Path));
            AssertHelper.ValidateIsNotNull(options.SerializeResponse, nameof(options.SerializeResponse));
            AssertHelper.ValidateIsNotNull(options.DeserializeRequest, nameof(options.DeserializeRequest));

            AssertHelper.ValidateIsNotEmpty(options.Path, nameof(options.Path));
        }
Пример #5
0
        public RpcMiddleware(RequestDelegate next, RpcEndpointOptions options, IRpcRequestRunner rpcCaller)
        {
            RpcMiddlewareValidator.ValidateOptions(options);
            RpcMiddlewareValidator.ValidateCaller(rpcCaller);

            this.rpcCaller = rpcCaller;
            this.options   = options;
            this.next      = next;
        }
        private static GRpcServer InitializeGrpcServer(RpcEndpointOptions options)
        {
            var grpcServer = new GRpcServer
            {
                Ports    = { new ServerPort(options.Address, options.Port, ServerCredentials.Insecure) },
                Services = { MagicOnionEngine.BuildServerServiceDefinition() }
            };

            grpcServer.Start();
            return(grpcServer);
        }
        /// <summary>
        /// Use <see cref="JsonSerializer"/> for deserializing requests and serializing responses.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="jsonOptions">Optional custom serialization settings.</param>
        /// <returns>The updated options.</returns>
        public static RpcEndpointOptions UseSystemJsonForDeserializeBody(this RpcEndpointOptions options, JsonSerializerOptions?jsonOptions = null)
        {
            jsonOptions ??= new JsonSerializerOptions();

            options.DeserializeRequest = async(request, cancellationToken) =>
            {
                var(requestType, context) = request;

                var hasContent = context.Request.ContentLength > 0;
                return(hasContent
                    ? await DeserializeJsonBody(requestType, context.Request.Body, jsonOptions, cancellationToken)
                    : CreateDefault(requestType));
            };

            return(options);
        }
Пример #8
0
        /// <summary>
        /// Here we use custom serialization code, in this case just use NewtonSoft's Json.NET.
        /// </summary>
        public static RpcEndpointOptions SerializeWithJsonNet(this RpcEndpointOptions options, JsonSerializerSettings settings)
        {
            options.DeserializeRequest = async(req, cancellationToken) =>
            {
                var(targetType, httpContext) = req;
                var request = httpContext.Request;

                if (request.ContentLength > 0)
                {
                    using var reader = new StreamReader(request.Body);
                    var body = await reader.ReadToEndAsync();

                    return(JsonConvert.DeserializeObject(body, targetType, settings));
                }

                return(Activator.CreateInstance(targetType));
            };

            return(options);
        }
Пример #9
0
        /// <summary>
        /// As we are using a custom common app response for all handlers, we can commonly handle special logic here.
        /// </summary>
        public static RpcEndpointOptions HandleCommonAppResponse(this RpcEndpointOptions options)
        {
            options.SerializeResponse = async(res, cancellationToken) =>
            {
                var(result, httpContext) = res;
                if (result is SuccessfullyProcessedRequestResult succResult)
                {
                    if (succResult.Response is CommonAppResponse response)
                    {
                        if (response.ValidationErrors.Any())
                        {
                            httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                            await httpContext.WriteAsJson(response.ValidationErrors, cancellationToken);
                        }
                        if (response.Response == null)
                        {
                            httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                        }

                        httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
                        await httpContext.WriteAsJson(response.Response, cancellationToken);
                    }
                    else
                    {
                        httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                    }
                }
                else if (result is NotFoundRequestResult notFoundResult)
                {
                    httpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                    await httpContext.Response.WriteAsync(notFoundResult.RequestName, cancellationToken);
                }
            };

            return(options);
        }
        public static IApplicationBuilder UseGrpcService(this IApplicationBuilder app, RpcEndpointOptions rpcEndpointOptions)
        {
            var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ??
                                      throw new ArgumentException("Missing Dependency", nameof(IApplicationLifetime));

            // 开启rpc服务
            var grpcServer = InitializeGrpcServer(rpcEndpointOptions);

            applicationLifetime.ApplicationStopping.Register(() =>
            {
                try
                {
                    grpcServer.ShutdownAsync().Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"grpcServer had shutown {ex}");
                }
            });

            return(app);
        }