Ejemplo n.º 1
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)
                });;
            };
        /// <summary>
        /// If the request was processed, the response is returned with http status code 200 (OK).
        /// Otherwise, http status code 404 - NotFound is returned with empty body.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <returns>The updated options.</returns>
        public static RpcHttpFunctionOptions UseOkorNotFoundActionResults(this RpcHttpFunctionOptions options)
        {
            options.SerializeResponse = (input, ct) =>
            {
                var(result, httpRequest) = input;

                IActionResult actionResult = result switch
                {
                    SuccessfullyProcessedRequestResult r => new OkObjectResult(r.Response),
                    NotFoundRequestResult r => new NotFoundObjectResult($"{r.RequestName} not found"),
                    _ => new OkObjectResult(result)
                };

                return(Task.FromResult(actionResult));
            };

            return(options);
        }
    }