-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommon.cs
More file actions
91 lines (85 loc) · 2.95 KB
/
Common.cs
File metadata and controls
91 lines (85 loc) · 2.95 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace NetPro.ResponseCache
{
internal class Common
{
internal static async Task<string> ReadAsString(HttpContext context)
{
try
{
if (context.Request.ContentLength > 0)
{
EnableRewind(context.Request);
var encoding = GetRequestEncoding(context.Request);
return await ReadStreamRequest(context, encoding);
}
return null;
}
catch (Exception ex) when (!ex.Message?.Replace(" ", string.Empty).ToLower().Contains("unexpectedendofrequestcontent") ?? true)
{
Console.WriteLine($"[ReadAsString] 共享请求body读取body出错");
return null;
}
}
internal static async Task<string> ReadStreamRequest(HttpContext context, Encoding encoding)
{
try
{
using (StreamReader sr = new StreamReader(context.Request.Body, encoding, true, 1024, true))
{
if (context.RequestAborted.IsCancellationRequested)
return null;
var str = await sr.ReadToEndAsync();
context.Request.Body.Seek(0, SeekOrigin.Begin);
return str;
}
}
catch (Exception)
{
return null;
}
}
internal static async Task<string> ReadStreamResponse(HttpContext context)
{
try
{
using (StreamReader sr = new StreamReader(context.Response.Body, Encoding.UTF8, true, 1024, true))
{
if (context.RequestAborted.IsCancellationRequested)
return null;
var str = await sr.ReadToEndAsync();
context.Response.Body.Seek(0, SeekOrigin.Begin);
return str;
}
}
catch (Exception)
{
return null;
}
}
internal static Encoding GetRequestEncoding(HttpRequest request)
{
var requestContentType = request.ContentType;
var requestMediaType = requestContentType == null ? default(MediaType) : new MediaType(requestContentType);
var requestEncoding = requestMediaType.Encoding;
if (requestEncoding == null)
{
requestEncoding = Encoding.UTF8;
}
return requestEncoding;
}
internal static void EnableRewind(HttpRequest request)
{
if (!request.Body.CanSeek)
{
request.EnableBuffering();
}
request.Body.Seek(0L, SeekOrigin.Begin);
}
}
}