forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomResultHandler.cs
More file actions
62 lines (53 loc) · 2.1 KB
/
CustomResultHandler.cs
File metadata and controls
62 lines (53 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Blog.Core.Gateway.Extensions
{
public class CustomResultHandler : DelegatingHandler
{
JsonSerializerSettings _camelSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() };
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
var contentType = response.Content.Headers.ContentType?.MediaType ?? "";
if (!contentType.Equals("application/json")) return response;
dynamic result = null;
var resultStr = await response.Content.ReadAsStringAsync();
try
{
Console.WriteLine(resultStr);
result = JsonConvert.DeserializeObject<dynamic>(resultStr);
}
catch (Exception)
{
return response;
}
if (result != null && result.errorCode == 500) resultStr = result.message.ToString();
var exception = new Exception(resultStr);
if (response.StatusCode == HttpStatusCode.InternalServerError || result.errorCode == (int)HttpStatusCode.InternalServerError)
{
var apiResult = new
{
Result = false,
Message = "服务器内部错误",
ErrorCode = (int)HttpStatusCode.InternalServerError,
Data = new
{
exception.Message,
exception.StackTrace
}
};
response.Content = new StringContent(JsonConvert.SerializeObject(apiResult, _camelSettings), Encoding.UTF8, "application/json");
}
else
{
}
return response;
}
}
}