|
| 1 | +using Blog.Core.Model; |
| 2 | +using Newtonsoft.Json; |
| 3 | +using Newtonsoft.Json.Serialization; |
| 4 | +using System; |
| 5 | +using System.Net; |
| 6 | +using System.Net.Http; |
| 7 | +using System.Text; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace Blog.Core.Gateway.Extensions |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// 这里不需要,目前集成的是 Blog.Core.Extensions 下的接口处理器 |
| 15 | + /// 但是你可以单独在网关中使用这个。 |
| 16 | + /// </summary> |
| 17 | + public class ApiResponseHandler : DelegatingHandler |
| 18 | + { |
| 19 | + JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() |
| 20 | + { |
| 21 | + ContractResolver = new CamelCasePropertyNamesContractResolver() |
| 22 | + }; |
| 23 | + |
| 24 | + protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 25 | + { |
| 26 | + var response = await base.SendAsync(request, cancellationToken); |
| 27 | + var contentType = response.Content.Headers.ContentType?.MediaType ?? ""; |
| 28 | + if (!contentType.Equals("application/json")) return response; |
| 29 | + |
| 30 | + dynamic result = null; |
| 31 | + var resultStr = await response.Content.ReadAsStringAsync(); |
| 32 | + try |
| 33 | + { |
| 34 | + result = JsonConvert.DeserializeObject<dynamic>(resultStr); |
| 35 | + } |
| 36 | + catch (Exception) |
| 37 | + { |
| 38 | + return response; |
| 39 | + } |
| 40 | + |
| 41 | + if (result != null && result.code == 500) resultStr = result.msg.ToString(); |
| 42 | + |
| 43 | + var apiResponse = new ApiResponse(StatusCode.CODE200).MessageModel; |
| 44 | + if (response.StatusCode != HttpStatusCode.OK || result.code == (int)HttpStatusCode.InternalServerError) |
| 45 | + { |
| 46 | + var exception = new Exception(resultStr); |
| 47 | + apiResponse = new ApiResponse(StatusCode.CODE500).MessageModel; |
| 48 | + } |
| 49 | + else if (result.code == (int)HttpStatusCode.Unauthorized) |
| 50 | + { |
| 51 | + apiResponse = new ApiResponse(StatusCode.CODE401).MessageModel; |
| 52 | + |
| 53 | + } |
| 54 | + else if (result.code == (int)HttpStatusCode.Forbidden) |
| 55 | + { |
| 56 | + apiResponse = new ApiResponse(StatusCode.CODE403).MessageModel; |
| 57 | + |
| 58 | + } |
| 59 | + else |
| 60 | + { |
| 61 | + |
| 62 | + } |
| 63 | + |
| 64 | + var statusCode = apiResponse.status == 500 ? HttpStatusCode.InternalServerError |
| 65 | + : apiResponse.status == 401 ? HttpStatusCode.Unauthorized |
| 66 | + : apiResponse.status == 403 ? HttpStatusCode.Forbidden |
| 67 | + : HttpStatusCode.OK; |
| 68 | + |
| 69 | + response.StatusCode = statusCode; |
| 70 | + response.Content = new StringContent(JsonConvert.SerializeObject(apiResponse, jsonSerializerSettings), Encoding.UTF8, "application/json"); |
| 71 | + |
| 72 | + return response; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + |
| 77 | +} |
0 commit comments