-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathHttpResult.cs
More file actions
531 lines (441 loc) · 16.4 KB
/
HttpResult.cs
File metadata and controls
531 lines (441 loc) · 16.4 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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using ServiceStack.Host;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack;
/// <summary>
/// Return a decorated HTTP Result to customize the HTTP Response
/// </summary>
public class HttpResult
: IHttpResult, IStreamWriterAsync, IPartialWriterAsync, IDisposable
{
public HttpResult()
: this((object)null, null) { }
public HttpResult(object response)
: this(response, null) { }
public HttpResult(object response, string contentType)
: this(response, contentType, HttpStatusCode.OK) { }
public HttpResult(HttpStatusCode statusCode, string statusDescription)
: this()
{
StatusCode = statusCode;
StatusDescription = statusDescription;
}
public HttpResult(object response, HttpStatusCode statusCode)
: this(response, null, statusCode) { }
public HttpResult(object response, string contentType, HttpStatusCode statusCode)
{
this.Headers = new Dictionary<string, string>();
this.Cookies = new List<Cookie>();
this.ResponseFilter = HostContext.AppHost?.ContentTypes ?? ContentTypes.Instance;
this.Response = response;
this.ContentType = contentType;
this.StatusCode = statusCode;
}
public HttpResult(FileInfo fileResponse, bool asAttachment)
: this(fileResponse, MimeTypes.GetMimeType(fileResponse.Name), asAttachment)
{ }
public HttpResult(FileInfo fileResponse, string contentType = null, bool asAttachment = false)
: this(null, contentType ?? MimeTypes.GetMimeType(fileResponse.Name), HttpStatusCode.OK)
{
this.FileInfo = fileResponse ?? throw new ArgumentNullException(nameof(fileResponse));
this.LastModified = fileResponse.LastWriteTime;
this.AllowsPartialResponse = true;
if (!FileInfo.Exists)
throw HttpError.NotFound($"{FileInfo.Name} was not found");
if (!asAttachment)
return;
var headerValue = $"attachment; {HttpExt.GetDispositionFileName(fileResponse.Name)}; size={fileResponse.Length}; " +
$"creation-date={fileResponse.CreationTimeUtc.ToString("R").Replace(",", "")}; " +
$"modification-date={fileResponse.LastWriteTimeUtc.ToString("R").Replace(",", "")}; " +
$"read-date={fileResponse.LastAccessTimeUtc.ToString("R").Replace(",", "")}";
this.Headers = new Dictionary<string, string>
{
{ HttpHeaders.ContentDisposition, headerValue },
};
}
public HttpResult(IVirtualFile fileResponse, bool asAttachment)
: this(fileResponse, MimeTypes.GetMimeType(fileResponse.Name), asAttachment)
{ }
public HttpResult(IVirtualFile fileResponse, string contentType = null, bool asAttachment = false)
: this(null, contentType ?? MimeTypes.GetMimeType(fileResponse.Name), HttpStatusCode.OK)
{
if (fileResponse == null)
throw new ArgumentNullException(nameof(fileResponse));
this.AllowsPartialResponse = true;
this.LastModified = fileResponse.LastModified;
this.VirtualFile = fileResponse;
this.ResponseStream = fileResponse.OpenRead();
if (!asAttachment) return;
var headerValue = $"attachment; {HttpExt.GetDispositionFileName(fileResponse.Name)}; size={fileResponse.Length}; modification-date={fileResponse.LastModified.ToString("R").Replace(",", "")}";
this.Headers = new Dictionary<string, string>
{
{ HttpHeaders.ContentDisposition, headerValue },
};
}
public HttpResult(Stream responseStream, string contentType)
: this(null, contentType, HttpStatusCode.OK)
{
this.AllowsPartialResponse = true;
this.ResponseStream = responseStream;
}
public HttpResult(string responseText, string contentType)
: this(null, contentType, HttpStatusCode.OK)
{
this.AllowsPartialResponse = true;
this.ResponseText = responseText;
}
public HttpResult(byte[] responseBytes, string contentType)
: this(null, contentType, HttpStatusCode.OK)
{
this.AllowsPartialResponse = true;
this.ResponseStream = MemoryStreamFactory.GetStream(responseBytes);
}
public string ResponseText { get; }
public Stream ResponseStream { get; private set; }
public FileInfo FileInfo { get; }
public IVirtualFile VirtualFile { get; }
public string ContentType { get; set; }
public Dictionary<string, string> Headers { get; }
public List<Cookie> Cookies { get; }
public string ETag { get; set; }
public TimeSpan? Age { get; set; }
public TimeSpan? MaxAge { get; set; }
public DateTime? Expires { get; set; }
public DateTime? LastModified { get; set; }
public CacheControl CacheControl { get; set; }
public Func<IDisposable> ResultScope { get; set; }
private bool allowsPartialResponse;
public bool AllowsPartialResponse
{
set
{
allowsPartialResponse = value;
if (allowsPartialResponse)
this.Headers.Add(HttpHeaders.AcceptRanges, "bytes");
else
this.Headers.Remove(HttpHeaders.AcceptRanges);
}
get => allowsPartialResponse;
}
public string Location
{
set
{
if (StatusCode == HttpStatusCode.OK)
StatusCode = HttpStatusCode.Redirect;
this.Headers[HttpHeaders.Location] = value;
}
}
public void SetPermanentCookie(string name, string value)
{
SetCookie(name, value, ServiceStack.Host.Cookies.PermanentCookieExpiry, null);
}
public void SetPermanentCookie(string name, string value, string path)
{
SetCookie(name, value, ServiceStack.Host.Cookies.PermanentCookieExpiry, path);
}
public void SetSessionCookie(string name, string value)
{
SetSessionCookie(name, value, null);
}
public void SetSessionCookie(string name, string value, string path)
{
path ??= "/";
this.Headers[HttpHeaders.SetCookie] = $"{name}={value};path={path}";
}
public void SetCookie(string name, string value, TimeSpan expiresIn, string path)
{
var expiresAt = DateTime.UtcNow.Add(expiresIn);
SetCookie(name, value, expiresAt, path);
}
public void SetCookie(string name, string value, DateTime expiresAt, string path, bool secure = false, bool httpOnly = false)
{
path ??= "/";
var cookie = $"{name}={value};expires={expiresAt:R};path={path}";
if (secure)
cookie += ";Secure";
if (httpOnly)
cookie += ";HttpOnly";
this.Headers[HttpHeaders.SetCookie] = cookie;
}
public void DeleteCookie(string name)
{
var cookie = $"{name}=;expires={DateTime.UtcNow.AddDays(-1):R};path=/";
this.Headers[HttpHeaders.SetCookie] = cookie;
}
public IDictionary<string, string> Options => this.Headers;
public int Status { get; set; }
public HttpStatusCode StatusCode
{
get => (HttpStatusCode)Status;
set => Status = (int)value;
}
public string StatusDescription { get; set; }
public object Response { get; set; }
public IContentTypeWriter ResponseFilter { get; set; }
public IRequest RequestContext { get; set; }
public string View { get; set; }
public string Template { get; set; }
public int PaddingLength { get; set; }
public async Task WriteToAsync(Stream responseStream, CancellationToken token = new())
{
try
{
await WriteToAsync(responseStream, PaddingLength, token).ConfigAwait();
await responseStream.FlushAsync(token).ConfigAwait();
}
finally
{
DisposeStream();
}
}
private async Task WriteToAsync(Stream responseStream, int paddingLength, CancellationToken token)
{
var response = RequestContext?.Response;
if (this.FileInfo != null)
{
response?.SetContentLength(FileInfo.Length + paddingLength);
using var fs = this.FileInfo.OpenRead();
await fs.CopyToAsync(responseStream, token).ConfigAwait();
return;
}
if (this.ResponseStream != null)
{
try
{
if (response != null)
{
if (ResponseStream is MemoryStream ms)
{
response.SetContentLength(ms.Length + paddingLength);
await ms.WriteToAsync(responseStream, token).ConfigAwait();
return;
}
}
await ResponseStream.CopyToAsync(responseStream, token).ConfigAwait();
}
finally
{
DisposeStream();
}
return;
}
if (this.ResponseText != null)
{
var bytes = Encoding.UTF8.GetBytes(this.ResponseText);
response?.SetContentLength(bytes.Length + paddingLength);
await responseStream.WriteAsync(bytes, token).ConfigAwait();
return;
}
if (this.ResponseFilter == null)
throw new ArgumentNullException(nameof(ResponseFilter));
if (this.RequestContext == null)
throw new ArgumentNullException(nameof(RequestContext));
if (this.Response is byte[] bytesResponse)
{
response?.SetContentLength(bytesResponse.Length + paddingLength);
await responseStream.WriteAsync(bytesResponse, token).ConfigAwait();
return;
}
if (View != null)
RequestContext.SetItem("View", View);
if (Template != null)
RequestContext.SetItem("Template", Template);
RequestContext.SetItem("HttpResult", this);
if (Response != null || View != null || Template != null) //allow new HttpResult { View = "/default.cshtml" }
{
await ResponseFilter.SerializeToStreamAsync(this.RequestContext, this.Response, responseStream).ConfigAwait();
}
}
public bool IsPartialRequest =>
AllowsPartialResponse && RequestContext.GetHeader(HttpHeaders.Range) != null && GetContentLength() != null;
public async Task WritePartialToAsync(IResponse response, CancellationToken token = default)
{
var contentLength = GetContentLength().GetValueOrDefault(int.MaxValue); //Safe as guarded by IsPartialRequest
var rangeHeader = RequestContext.GetHeader(HttpHeaders.Range);
rangeHeader.ExtractHttpRanges(contentLength, out var rangeStart, out var rangeEnd);
if (rangeEnd > contentLength - 1)
rangeEnd = contentLength - 1;
response.AddHttpRangeResponseHeaders(rangeStart, rangeEnd, contentLength);
var outputStream = response.OutputStream;
if (VirtualFile != null)
{
try
{
await VirtualFile.WritePartialToAsync(outputStream, rangeStart, rangeEnd, token).ConfigAwait();
}
finally
{
DisposeStream();
}
}
else if (FileInfo != null)
{
using var fs = FileInfo.OpenRead();
await fs.WritePartialToAsync(outputStream, rangeStart, rangeEnd, token).ConfigAwait();
}
else if (ResponseStream != null)
{
try
{
await ResponseStream.WritePartialToAsync(outputStream, rangeStart, rangeEnd, token).ConfigAwait();
}
finally
{
DisposeStream();
}
}
else if (ResponseText != null)
{
using var ms = MemoryStreamFactory.GetStream(Encoding.UTF8.GetBytes(ResponseText));
await ms.WritePartialToAsync(outputStream, rangeStart, rangeEnd, token).ConfigAwait();
}
else
throw new InvalidOperationException("Neither file, stream nor text were set when attempting to write to the Response Stream.");
}
public long? GetContentLength()
{
if (FileInfo != null)
return FileInfo.Length;
if (ResponseStream != null)
return ResponseStream.Length;
return ResponseText?.Length;
}
public static HttpResult Status201Created(object response, string newLocationUri)
{
return new HttpResult(response)
{
StatusCode = HttpStatusCode.Created,
Headers =
{
{ HttpHeaders.Location, newLocationUri },
}
};
}
public static HttpResult Redirect(string newLocationUri, HttpStatusCode redirectStatus = HttpStatusCode.Found)
{
return new HttpResult
{
StatusCode = redirectStatus,
Headers =
{
{ HttpHeaders.Location, newLocationUri },
}
};
}
/// <summary>
/// Respond with a 'Soft redirect' so smart clients (e.g. ajax) have access to the response and
/// can decide whether or not they should redirect
/// </summary>
public static HttpResult SoftRedirect(string newLocationUri, object response = null)
{
return new HttpResult(response)
{
Headers =
{
{ HttpHeaders.XLocation, newLocationUri },
}
};
}
/// <summary>
/// Decorate the response with an additional client-side event to instruct participating
/// smart clients (e.g. ajax) with hints to transparently invoke client-side functionality
/// </summary>
public static HttpResult TriggerEvent(object response, string eventName, string value = null)
{
return new HttpResult(response)
{
Headers =
{
{ HttpHeaders.XTrigger, eventName + (value != null ? ":" + value : "") },
}
};
}
public static HttpResult NotModified(string description = null,
CacheControl? cacheControl = null,
TimeSpan? maxAge = null,
string eTag = null,
DateTime? lastModified = null)
{
return new HttpResult(HttpStatusCode.NotModified,
description ?? HostContext.ResolveLocalizedString(LocalizedStrings.NotModified))
{
ETag = eTag,
LastModified = lastModified,
MaxAge = maxAge,
CacheControl = cacheControl.GetValueOrDefault(CacheControl.None),
};
}
private void DisposeStream()
{
try
{
if (ResponseStream == null) return;
this.ResponseStream.Dispose();
this.ResponseStream = null;
}
catch { /*ignore*/ }
}
public void Dispose()
{
DisposeStream();
using (Response as IDisposable) {}
}
}
[Flags]
public enum CacheControl : long
{
None = 0,
Public = 1 << 0,
Private = 1 << 1,
MustRevalidate = 1 << 2,
NoCache = 1 << 3,
NoStore = 1 << 4,
NoTransform = 1 << 5,
ProxyRevalidate = 1 << 6,
}
public static class HttpResultExtensions
{
#if !NETCORE
public static System.Net.Cookie ToCookie(this HttpCookie httpCookie)
{
var to = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path)
{
Expires = httpCookie.Expires,
Secure = httpCookie.Secure,
HttpOnly = httpCookie.HttpOnly,
};
if (httpCookie.Domain != null)
to.Domain = httpCookie.Domain;
return to;
}
#endif
public static IHttpResult AddCookie(this IHttpResult httpResult, IRequest req, Cookie cookie)
{
var appHost = HostContext.AppHost;
if (appHost == null || appHost.SetCookieFilter(req, cookie))
httpResult.Cookies.Add(cookie);
return httpResult;
}
public static IHttpResult DeleteCookie(this IHttpResult httpResult, IRequest req, string cookieName)
{
var cookies = (Cookies)((IHttpResponse)req.Response).Cookies;
httpResult.Cookies.Add(new Cookie(cookieName, string.Empty, Cookies.RootPath)
{
Expires = DateTime.UtcNow.AddDays(-1),
Secure = cookies.UseSecureCookie(null)
});
cookies.Collection.RemoveAll(x => x.Name == cookieName);
return httpResult;
}
}