private async Task HandleExceptionAsync(HttpContext context, ApiException exception) { ConsistentApiResponse response = exception.As <IConsistentable>().GetConsistentApiResponse(); _responseHelper.FormatResponseAccordingToOptions(ref response, exception.StatusCode); _logger.LogError(exception, ResponseMessage.GetResponseMessageByStatusCode(response.StatusCode)); string serializedResponse = JsonHelper.ConvertResponseToJsonString(response, _options); await _responseHelper.WriteFormattedResponseToHttpContextAsync(context, exception.StatusCode, serializedResponse); }
internal static string ConvertResponseToJsonString(ConsistentApiResponse response, ResponseOptions options) => JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings() { Converters = new List <JsonConverter> { new StringEnumConverter() }, NullValueHandling = options.IgnoreNullValue ? NullValueHandling.Ignore : NullValueHandling.Include, ContractResolver = options.UseCamelCaseNaming ? new CamelCasePropertyNamesContractResolver() : new DefaultContractResolver() });
internal void FormatResponseAccordingToOptions(ref ConsistentApiResponse response, int statusCode) { if (statusCode != StatusCodes.Status200OK && string.IsNullOrEmpty(response.Message)) { response.Message = ResponseMessage.GetResponseMessageByStatusCode(statusCode); } response.Version = !_options.ShowApiVersion ? null : response.Version ?? _options.ApiVersion; response.StatusCode = _options.ShowStatusCode ? statusCode : default; response.ExceptionDetails = _options.IsDebug ? response.ExceptionDetails : null; }
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); }