Ejemplo n.º 1
0
        private async Task HandleRequestAsync(HttpContext context, string body)
        {
            if (!_responseHelper.IsConsistentlyResponse(body, context.Response.ContentType))
            {
                await context.Response.WriteAsync(body);

                return;
            }

            ConsistentApiResponse response = null;
            int httpStatusCode             = context.Response.StatusCode == StatusCodes.Status204NoContent
                ? StatusCodes.Status200OK
                : context.Response.StatusCode;

            if (!string.IsNullOrEmpty(body))
            {
                string bodyText             = !body.IsValidJson() ? JsonHelper.ConvertToJsonString(body) : body;
                JToken deserializedResponse = JsonConvert.DeserializeObject <JToken>(bodyText);

                if (deserializedResponse is JObject responseObj)
                {
                    Type type = responseObj["$type"]?.ToObject <Type>();

                    if (type != null && typeof(IConsistentable).IsAssignableFrom(type))
                    {
                        response = deserializedResponse.ToObject(type)
                                   .As <IConsistentable>()
                                   .GetConsistentApiResponse();
                    }
                }

                response ??= JsonHelper.GetConsistentApiResponseFromJsonToken(deserializedResponse);
            }
            else
            {
                response = new ConsistentApiResponse();
            }

            _responseHelper.FormatResponseAccordingToOptions(ref response, httpStatusCode);

            string serializedResponse = JsonHelper.ConvertResponseToJsonString(response, _options);
            await _responseHelper.WriteFormattedResponseToHttpContextAsync(context, response.StatusCode ?? httpStatusCode, serializedResponse);
        }