forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpResultUtils.cs
More file actions
195 lines (166 loc) · 7.7 KB
/
HttpResultUtils.cs
File metadata and controls
195 lines (166 loc) · 7.7 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Text.Pools;
using ServiceStack.Web;
namespace ServiceStack
{
public static class HttpResultUtils
{
/// <summary>
/// Shortcut to get the ResponseDTO whether it's bare or inside a IHttpResult
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static object GetDto(this object response)
{
if (response == null) return null;
return response is IHttpResult httpResult ? httpResult.Response : response;
}
/// <summary>
/// Alias of AsDto
/// </summary>
public static object GetResponseDto(this object response)
{
return GetDto(response);
}
/// <summary>
/// Shortcut to get the ResponseDTO whether it's bare or inside a IHttpResult
/// </summary>
/// <param name="response"></param>
/// <returns>TResponse if found; otherwise null</returns>
public static TResponse GetDto<TResponse>(this object response) where TResponse : class
{
if (response == null) return default(TResponse);
return (response is IHttpResult httpResult ? httpResult.Response : response) as TResponse;
}
/// <summary>
/// Alias of AsDto
/// </summary>
public static TResponse GetResponseDto<TResponse>(this object response) where TResponse : class
{
return GetDto<TResponse>(response);
}
public static object CreateErrorResponse(this IHttpError httpError)
{
if (httpError == null) return null;
var errorDto = httpError.GetDto();
if (errorDto != null) return errorDto;
return new ErrorResponse
{
ResponseStatus = new ResponseStatus
{
ErrorCode = httpError.ErrorCode,
Message = httpError.Message,
StackTrace = httpError.StackTrace,
}
};
}
/// <summary>
/// Whether the response is an IHttpError or Exception
/// </summary>
public static bool IsErrorResponse(this object response)
{
return response != null && (response is IHttpError || response is Exception);
}
/// <summary>
/// rangeHeader should be of the format "bytes=0-" or "bytes=0-12345" or "bytes=123-456"
/// </summary>
public static void ExtractHttpRanges(this string rangeHeader, long contentLength, out long rangeStart, out long rangeEnd)
{
var rangeParts = rangeHeader.RightPart("=").SplitOnFirst("-");
rangeStart = long.Parse(rangeParts[0]);
rangeEnd = rangeParts.Length == 2 && !string.IsNullOrEmpty(rangeParts[1])
? int.Parse(rangeParts[1]) //the client requested a chunk
: contentLength - 1;
}
/// <summary>
/// Adds 206 PartialContent Status, Content-Range and Content-Length headers
/// </summary>
public static void AddHttpRangeResponseHeaders(this IResponse response, long rangeStart, long rangeEnd, long contentLength)
{
response.AddHeader(HttpHeaders.ContentRange, $"bytes {rangeStart}-{rangeEnd}/{contentLength}");
response.StatusCode = (int)HttpStatusCode.PartialContent;
response.SetContentLength(rangeEnd - rangeStart + 1);
}
/// <summary>
/// Writes partial range as specified by start-end, from fromStream to toStream.
/// </summary>
[Obsolete("Use WritePartialToAsync")]
public static void WritePartialTo(this Stream fromStream, Stream toStream, long start, long end)
{
if (!fromStream.CanSeek)
throw new InvalidOperationException(
"Sending Range Responses requires a seekable stream eg. FileStream or MemoryStream");
long totalBytesToSend = end - start + 1;
var buf = SharedPools.AsyncByteArray.Allocate();
long bytesRemaining = totalBytesToSend;
fromStream.Seek(start, SeekOrigin.Begin);
while (bytesRemaining > 0)
{
var count = bytesRemaining <= buf.Length
? fromStream.Read(buf, 0, (int)Math.Min(bytesRemaining, int.MaxValue))
: fromStream.Read(buf, 0, buf.Length);
try
{
//Log.DebugFormat("Writing {0} to response",System.Text.Encoding.UTF8.GetString(buffer));
toStream.Write(buf, 0, count);
toStream.Flush();
bytesRemaining -= count;
}
catch (Exception httpException)
{
/* in Asp.Net we can call HttpResponseBase.IsClientConnected
* to see if the client broke off the connection
* and avoid trying to flush the response stream.
* I'm not quite I can do the same here without some invasive changes,
* so instead I'll swallow the exception that IIS throws in this situation.*/
if (httpException.Message == "An error occurred while communicating with the remote host. The error code is 0x80070057.")
return;
throw;
}
}
SharedPools.AsyncByteArray.Free(buf);
}
/// <summary>
/// Writes partial range as specified by start-end, from fromStream to toStream.
/// </summary>
public static async Task WritePartialToAsync(this Stream fromStream, Stream toStream, long start, long end, CancellationToken token = default(CancellationToken))
{
if (!fromStream.CanSeek)
throw new InvalidOperationException(
"Sending Range Responses requires a seekable stream eg. FileStream or MemoryStream");
long totalBytesToSend = end - start + 1;
var buf = SharedPools.AsyncByteArray.Allocate();
long bytesRemaining = totalBytesToSend;
fromStream.Seek(start, SeekOrigin.Begin);
while (bytesRemaining > 0)
{
try
{
var count = bytesRemaining <= buf.Length
? await fromStream.ReadAsync(buf, 0, (int)Math.Min(bytesRemaining, int.MaxValue), token)
: await fromStream.ReadAsync(buf, 0, buf.Length, token);
//Log.DebugFormat("Writing {0} to response",System.Text.Encoding.UTF8.GetString(buffer));
await toStream.WriteAsync(buf, 0, count, token);
await toStream.FlushAsync(token);
bytesRemaining -= count;
}
catch (Exception httpException)
{
/* in Asp.Net we can call HttpResponseBase.IsClientConnected
* to see if the client broke off the connection
* and avoid trying to flush the response stream.
* I'm not quite I can do the same here without some invasive changes,
* so instead I'll swallow the exception that IIS throws in this situation.*/
if (httpException.Message == "An error occurred while communicating with the remote host. The error code is 0x80070057.")
return;
throw;
}
}
SharedPools.AsyncByteArray.Free(buf);
}
}
}