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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
|
//Copyright (c) Service Stack LLC. All Rights Reserved.
//License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using MediaBrowser.Model.Services;
using ServiceStack.Host;
namespace ServiceStack
{
public static class HttpResponseExtensionsInternal
{
public static async Task<bool> WriteToOutputStream(IResponse response, object result)
{
var asyncStreamWriter = result as IAsyncStreamWriter;
if (asyncStreamWriter != null)
{
await asyncStreamWriter.WriteToAsync(response.OutputStream, CancellationToken.None).ConfigureAwait(false);
return true;
}
var streamWriter = result as IStreamWriter;
if (streamWriter != null)
{
streamWriter.WriteTo(response.OutputStream);
return true;
}
var stream = result as Stream;
if (stream != null)
{
WriteTo(stream, response.OutputStream);
return true;
}
var bytes = result as byte[];
if (bytes != null)
{
response.ContentType = "application/octet-stream";
response.SetContentLength(bytes.Length);
response.OutputStream.Write(bytes, 0, bytes.Length);
return true;
}
return false;
}
public static long WriteTo(Stream inStream, Stream outStream)
{
var memoryStream = inStream as MemoryStream;
if (memoryStream != null)
{
memoryStream.WriteTo(outStream);
return memoryStream.Position;
}
var data = new byte[4096];
long total = 0;
int bytesRead;
while ((bytesRead = inStream.Read(data, 0, data.Length)) > 0)
{
outStream.Write(data, 0, bytesRead);
total += bytesRead;
}
return total;
}
/// <summary>
/// End a ServiceStack Request with no content
/// </summary>
public static void EndRequestWithNoContent(this IResponse httpRes)
{
if (httpRes.StatusCode == (int)HttpStatusCode.OK)
{
httpRes.StatusCode = (int)HttpStatusCode.NoContent;
}
httpRes.SetContentLength(0);
}
public static Task WriteToResponse(this IResponse httpRes, MediaBrowser.Model.Services.IRequest httpReq, object result)
{
if (result == null)
{
httpRes.EndRequestWithNoContent();
return Task.FromResult(true);
}
var httpResult = result as IHttpResult;
if (httpResult != null)
{
httpResult.RequestContext = httpReq;
httpReq.ResponseContentType = httpResult.ContentType ?? httpReq.ResponseContentType;
var httpResSerializer = ContentTypes.Instance.GetResponseSerializer(httpReq.ResponseContentType);
return httpRes.WriteToResponse(httpResult, httpResSerializer, httpReq);
}
var serializer = ContentTypes.Instance.GetResponseSerializer(httpReq.ResponseContentType);
return httpRes.WriteToResponse(result, serializer, httpReq);
}
private static object GetDto(object response)
{
if (response == null) return null;
var httpResult = response as IHttpResult;
return httpResult != null ? httpResult.Response : response;
}
/// <summary>
/// Writes to response.
/// Response headers are customizable by implementing IHasHeaders an returning Dictionary of Http headers.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param>
/// <param name="defaultAction">The default action.</param>
/// <param name="request">The serialization context.</param>
/// <returns></returns>
public static async Task WriteToResponse(this IResponse response, object result, Action<IRequest, object, IResponse> defaultAction, MediaBrowser.Model.Services.IRequest request)
{
var defaultContentType = request.ResponseContentType;
if (result == null)
{
response.EndRequestWithNoContent();
return;
}
var httpResult = result as IHttpResult;
if (httpResult != null)
{
if (httpResult.RequestContext == null)
httpResult.RequestContext = request;
response.Dto = response.Dto ?? GetDto(httpResult);
response.StatusCode = httpResult.Status;
response.StatusDescription = httpResult.StatusDescription ?? httpResult.StatusCode.ToString();
if (string.IsNullOrEmpty(httpResult.ContentType))
{
httpResult.ContentType = defaultContentType;
}
response.ContentType = httpResult.ContentType;
if (httpResult.Cookies != null)
{
var httpRes = response as IHttpResponse;
if (httpRes != null)
{
foreach (var cookie in httpResult.Cookies)
{
httpRes.SetCookie(cookie);
}
}
}
}
else
{
response.Dto = result;
}
/* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
var responseOptions = result as IHasHeaders;
if (responseOptions != null)
{
//Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
const string reservedOptions = ".";
foreach (var responseHeaders in responseOptions.Headers)
{
if (responseHeaders.Key.Contains(reservedOptions)) continue;
if (responseHeaders.Key == "Content-Length")
{
response.SetContentLength(long.Parse(responseHeaders.Value));
continue;
}
response.AddHeader(responseHeaders.Key, responseHeaders.Value);
}
}
//ContentType='text/html' is the default for a HttpResponse
//Do not override if another has been set
if (response.ContentType == null || response.ContentType == "text/html")
{
response.ContentType = defaultContentType;
}
if (new HashSet<string> { "application/json", }.Contains(response.ContentType))
{
response.ContentType += "; charset=utf-8";
}
var disposableResult = result as IDisposable;
var writeToOutputStreamResult = await WriteToOutputStream(response, result).ConfigureAwait(false);
if (writeToOutputStreamResult)
{
response.Flush(); //required for Compression
if (disposableResult != null) disposableResult.Dispose();
return;
}
if (httpResult != null)
result = httpResult.Response;
var responseText = result as string;
if (responseText != null)
{
if (response.ContentType == null || response.ContentType == "text/html")
response.ContentType = defaultContentType;
response.Write(responseText);
return;
}
if (defaultAction == null)
{
throw new ArgumentNullException("defaultAction", String.Format(
"As result '{0}' is not a supported responseType, a defaultAction must be supplied",
(result != null ? result.GetType().GetOperationName() : "")));
}
if (result != null)
defaultAction(request, result, response);
if (disposableResult != null)
disposableResult.Dispose();
}
}
}
|