forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRequestExtensions.cs
More file actions
1067 lines (902 loc) · 39 KB
/
HttpRequestExtensions.cs
File metadata and controls
1067 lines (902 loc) · 39 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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.Hosting;
using ServiceStack.Data;
using ServiceStack.Host;
using ServiceStack.Host.AspNet;
using ServiceStack.Host.Handlers;
using ServiceStack.Host.HttpListener;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.Model;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack
{
public static class HttpRequestExtensions
{
/// <summary>
/// Gets string value from Items[name] then Cookies[name] if exists.
/// Useful when *first* setting the users response cookie in the request filter.
/// To access the value for this initial request you need to set it in Items[].
/// </summary>
/// <returns>string value or null if it doesn't exist</returns>
public static string GetItemOrCookie(this IRequest httpReq, string name)
{
object value;
if (httpReq.Items.TryGetValue(name, out value)) return value.ToString();
Cookie cookie;
if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value;
return null;
}
/// <summary>
/// Gets request paramater string value by looking in the following order:
/// - QueryString[name]
/// - FormData[name]
/// - Cookies[name]
/// - Items[name]
/// </summary>
/// <returns>string value or null if it doesn't exist</returns>
public static string GetParam(this IRequest httpReq, string name)
{
string value;
if ((value = httpReq.Headers[HttpHeaders.XParamOverridePrefix + name]) != null) return value;
if ((value = httpReq.QueryString[name]) != null) return value;
if ((value = httpReq.FormData[name]) != null) return value;
//IIS will assign null to params without a name: .../?some_value can be retrieved as req.Params[null]
//TryGetValue is not happy with null dictionary keys, so we should bail out here
if (string.IsNullOrEmpty(name)) return null;
Cookie cookie;
if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value;
object oValue;
if (httpReq.Items.TryGetValue(name, out oValue)) return oValue.ToString();
return null;
}
public static string GetParentAbsolutePath(this IRequest httpReq)
{
return httpReq.GetAbsolutePath().ToParentPath();
}
public static string GetAbsolutePath(this IRequest httpReq)
{
var resolvedPathInfo = httpReq.PathInfo;
var pos = httpReq.RawUrl.IndexOf(resolvedPathInfo, StringComparison.OrdinalIgnoreCase);
if (pos == -1)
throw new ArgumentException(
String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl));
return httpReq.RawUrl.Substring(0, pos + resolvedPathInfo.Length);
}
public static string GetParentPathUrl(this IRequest httpReq)
{
return httpReq.GetPathUrl().ToParentPath();
}
public static string GetPathUrl(this IRequest httpReq)
{
var resolvedPathInfo = httpReq.PathInfo.TrimEnd('/');
int pos;
if (resolvedPathInfo == string.Empty)
{
pos = httpReq.AbsoluteUri.IndexOf('?');
if (pos == -1)
pos = httpReq.AbsoluteUri.Length;
}
else
{
pos = httpReq.AbsoluteUri.IndexOf(resolvedPathInfo, StringComparison.OrdinalIgnoreCase);
}
if (pos == -1)
throw new ArgumentException(
String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl));
return httpReq.AbsoluteUri.Substring(0, pos + resolvedPathInfo.Length);
}
public static string GetUrlHostName(this IRequest httpReq)
{
var aspNetReq = httpReq as AspNetRequest;
if (aspNetReq != null)
{
return aspNetReq.UrlHostName;
}
var uri = httpReq.AbsoluteUri;
var pos = uri.IndexOf("://") + "://".Length;
var partialUrl = uri.Substring(pos);
var endPos = partialUrl.IndexOf('/');
if (endPos == -1) endPos = partialUrl.Length;
var hostName = partialUrl.Substring(0, endPos).Split(':')[0];
return hostName;
}
public static string GetPhysicalPath(this IRequest httpReq)
{
return HostContext.ResolvePhysicalPath(httpReq.PathInfo, httpReq);
}
public static IVirtualFile GetVirtualFile(this IRequest httpReq)
{
return HostContext.ResolveVirtualFile(httpReq.PathInfo, httpReq);
}
public static IVirtualDirectory GetVirtualDirectory(this IRequest httpReq)
{
return HostContext.ResolveVirtualDirectory(httpReq.PathInfo, httpReq);
}
public static IVirtualNode GetVirtualNode(this IRequest httpReq)
{
return HostContext.ResolveVirtualNode(httpReq.PathInfo, httpReq);
}
public static string GetDirectoryPath(this IRequest request)
{
if (request == null)
return null;
var path = request.PathInfo;
return string.IsNullOrEmpty(path) || path[path.Length - 1] == '/'
? path
: path.Substring(0, path.LastIndexOf('/') + 1);
}
//http://stackoverflow.com/a/757251/85785
static readonly string[] VirtualPathPrefixes = HostingEnvironment.ApplicationVirtualPath == null || HostingEnvironment.ApplicationVirtualPath == "/"
? TypeConstants.EmptyStringArray
: new[] { HostingEnvironment.ApplicationVirtualPath, "~" + HostingEnvironment.ApplicationVirtualPath };
public static string SanitizedVirtualPath(this string virtualPath)
{
return HostContext.Config.StripApplicationVirtualPath
? virtualPath.TrimPrefixes(VirtualPathPrefixes)
: virtualPath;
}
public static string GetApplicationUrl(this HttpRequestBase httpReq)
{
var appPath = httpReq.ApplicationPath.SanitizedVirtualPath();
var baseUrl = httpReq.Url.GetLeftPart(UriPartial.Authority);
baseUrl = baseUrl.CombineWith(appPath, HostContext.Config.HandlerFactoryPath);
return baseUrl;
}
public static string GetApplicationUrl(this IRequest httpReq)
{
var url = new Uri(httpReq.AbsoluteUri);
var baseUrl = url.GetLeftPart(UriPartial.Authority);
var appUrl = baseUrl.CombineWith(HostContext.Config.HandlerFactoryPath);
return appUrl;
}
public static string GetHttpMethodOverride(this IRequest httpReq)
{
var httpMethod = httpReq.Verb;
if (httpMethod != HttpMethods.Post)
return httpMethod;
var overrideHttpMethod =
httpReq.Headers[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty()
?? httpReq.FormData[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty()
?? httpReq.QueryString[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty();
if (overrideHttpMethod != null)
{
if (overrideHttpMethod != HttpMethods.Get && overrideHttpMethod != HttpMethods.Post)
httpMethod = overrideHttpMethod;
}
return httpMethod;
}
public static string GetFormatModifier(this IRequest httpReq)
{
var format = httpReq.QueryString[Keywords.Format];
if (format == null)
return null;
var pos = format.IndexOf('.');
return pos >= 0 ? format.Substring(pos + 1) : null;
}
public static bool HasNotModifiedSince(this IRequest httpReq, DateTime? dateTime)
{
if (!dateTime.HasValue) return false;
var strHeader = httpReq.Headers[HttpHeaders.IfModifiedSince];
try
{
if (strHeader != null)
{
var dateIfModifiedSince = DateTime.ParseExact(strHeader, "r", null);
var utcFromDate = dateTime.Value.ToUniversalTime();
//strip ms
utcFromDate = new DateTime(
utcFromDate.Ticks - (utcFromDate.Ticks % TimeSpan.TicksPerSecond),
utcFromDate.Kind
);
return utcFromDate <= dateIfModifiedSince;
}
return false;
}
catch
{
return false;
}
}
public static bool DidReturn304NotModified(this IRequest httpReq, DateTime? dateTime, IResponse httpRes)
{
if (httpReq.HasNotModifiedSince(dateTime))
{
httpRes.StatusCode = (int)HttpStatusCode.NotModified;
return true;
}
return false;
}
public static string GetJsonpCallback(this IRequest httpReq)
{
return httpReq == null ? null : httpReq.QueryString[Keywords.Callback];
}
public static Dictionary<string, string> CookiesAsDictionary(this IRequest httpReq)
{
var map = new Dictionary<string, string>();
var aspNet = httpReq.OriginalRequest as HttpRequest;
if (aspNet != null)
{
foreach (var name in aspNet.Cookies.AllKeys)
{
var cookie = aspNet.Cookies[name];
if (cookie == null) continue;
map[name] = cookie.Value;
}
}
else
{
var httpListener = httpReq.OriginalRequest as HttpListenerRequest;
if (httpListener != null)
{
for (var i = 0; i < httpListener.Cookies.Count; i++)
{
var cookie = httpListener.Cookies[i];
if (cookie == null || cookie.Name == null) continue;
map[cookie.Name] = cookie.Value;
}
}
}
return map;
}
public static int ToStatusCode(this Exception ex)
{
var hasStatusCode = ex as IHasStatusCode;
if (hasStatusCode != null)
return hasStatusCode.StatusCode;
if (HostContext.Config != null)
{
var exType = ex.GetType();
foreach (var entry in HostContext.Config.MapExceptionToStatusCode)
{
if (entry.Key.IsAssignableFromType(exType))
return entry.Value;
}
}
if (ex is HttpError) return ((HttpError)ex).Status;
if (ex is NotImplementedException || ex is NotSupportedException) return (int)HttpStatusCode.MethodNotAllowed;
if (ex is ArgumentException || ex is SerializationException || ex is FormatException) return (int)HttpStatusCode.BadRequest;
if (ex is AuthenticationException) return (int)HttpStatusCode.Unauthorized;
if (ex is UnauthorizedAccessException) return (int)HttpStatusCode.Forbidden;
if (ex is OptimisticConcurrencyException) return (int)HttpStatusCode.Conflict;
return (int)HttpStatusCode.InternalServerError;
}
public static string ToErrorCode(this Exception ex)
{
var hasErrorCode = ex as IHasErrorCode;
return (hasErrorCode != null ? hasErrorCode.ErrorCode : null)
?? ex.GetType().Name;
}
public static WebServiceException ToWebServiceException(this HttpError error)
{
var to = new WebServiceException(error.Message, error.InnerException)
{
StatusCode = error.Status,
StatusDescription = error.StatusDescription,
ResponseDto = error.Response,
};
return to;
}
/**
*
Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment
Some HttpRequest path and URL properties:
Request.ApplicationPath: /Cambia3
Request.CurrentExecutionFilePath: /Cambia3/Temp/Test.aspx
Request.FilePath: /Cambia3/Temp/Test.aspx
Request.Path: /Cambia3/Temp/Test.aspx/path/info
Request.PathInfo: /path/info
Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\Cambia3\
Request.QueryString: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.AbsolutePath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.AbsoluteUri: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Fragment:
Request.Url.Host: localhost
Request.Url.LocalPath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.PathAndQuery: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Port: 96
Request.Url.Query: ?query=arg
Request.Url.Scheme: http
Request.Url.Segments: /
Cambia3/
Temp/
Test.aspx/
path/
info
* */
private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions));
private static string WebHostDirectoryName = "";
static HttpRequestExtensions()
{
WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath());
}
public static string GetOperationName(this HttpRequestBase request)
{
var pathInfo = request.GetLastPathInfo();
return GetOperationNameFromLastPathInfo(pathInfo);
}
public static string GetOperationNameFromLastPathInfo(string lastPathInfo)
{
if (String.IsNullOrEmpty(lastPathInfo)) return null;
var operationName = lastPathInfo.Substring("/".Length);
return operationName;
}
private static string GetLastPathInfoFromRawUrl(string rawUrl)
{
var pathInfo = rawUrl.IndexOf("?") != -1
? rawUrl.Substring(0, rawUrl.IndexOf("?"))
: rawUrl;
pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/"));
return pathInfo;
}
public static string GetLastPathInfo(this HttpRequestBase request)
{
var pathInfo = request.PathInfo;
if (String.IsNullOrEmpty(pathInfo))
{
pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl);
}
//Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}",
// request.PathInfo, request.RawUrl, pathInfo);
return pathInfo;
}
public static string GetUrlHostName(this HttpRequestBase request)
{
//TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host'
try
{
return request.Url.Host;
}
catch (Exception ex)
{
Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex);
return request.UserHostName;
}
}
// http://localhost/ServiceStack.Examples.Host.Web/Public/Public/Soap12/Wsdl =>
// http://localhost/ServiceStack.Examples.Host.Web/Public/Soap12/
public static string GetParentBaseUrl(this HttpRequestBase request)
{
var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); // /Cambia3/Temp/Test.aspx/path
return GetAuthority(request) + endpointsPath;
}
public static string GetParentBaseUrl(this IRequest request)
{
var rawUrl = request.RawUrl;
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1);
return new Uri(request.AbsoluteUri).GetLeftPart(UriPartial.Authority) + endpointsPath;
}
public static string GetBaseUrl(this HttpRequestBase request)
{
return GetAuthority(request) + request.RawUrl;
}
//=> http://localhost:96 ?? ex=> http://localhost
private static string GetAuthority(HttpRequestBase request)
{
try
{
return request.Url.GetLeftPart(UriPartial.Authority);
}
catch (Exception ex)
{
Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex);
return "http://" + request.UserHostName;
}
}
public static string GetOperationName(this HttpListenerRequest request)
{
return request.Url.Segments[request.Url.Segments.Length - 1];
}
public static string GetLastPathInfo(this HttpListenerRequest request)
{
return GetLastPathInfoFromRawUrl(request.RawUrl);
}
public static string GetPathInfo(this HttpRequestBase request)
{
if (!String.IsNullOrEmpty(request.PathInfo)) return request.PathInfo.TrimEnd('/');
var mode = HostContext.Config.HandlerFactoryPath;
var appPath = String.IsNullOrEmpty(request.ApplicationPath)
? WebHostDirectoryName
: request.ApplicationPath.TrimStart('/');
//mod_mono: /CustomPath35/api//default.htm
var path = Env.IsMono ? request.Path.Replace("//", "/") : request.Path;
return GetPathInfo(path, mode, appPath);
}
public static string GetPathInfo(string fullPath, string mode, string appPath)
{
var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
if (!String.IsNullOrEmpty(pathInfo)) return pathInfo;
//Wildcard mode relies on this to work out the handlerPath
pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
if (!String.IsNullOrEmpty(pathInfo)) return pathInfo;
return fullPath;
}
public static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
{
if (mappedPathRoot == null) return null;
var sbPathInfo = StringBuilderCache.Allocate();
var fullPathParts = fullPath.Split('/');
var mappedPathRootParts = mappedPathRoot.Split('/');
var fullPathIndexOffset = mappedPathRootParts.Length - 1;
var pathRootFound = false;
for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
{
if (pathRootFound)
{
sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
}
else if (fullPathIndex - fullPathIndexOffset >= 0)
{
pathRootFound = true;
for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
{
if (!String.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
{
pathRootFound = false;
break;
}
}
}
}
if (!pathRootFound) return null;
var path = StringBuilderCache.ReturnAndFree(sbPathInfo);
return path.Length > 1 ? path.TrimEnd('/') : "/";
}
public static bool IsContentType(this IRequest request, string contentType)
{
return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
}
public static bool HasAnyOfContentTypes(this IRequest request, params string[] contentTypes)
{
if (contentTypes == null || request.ContentType == null) return false;
foreach (var contentType in contentTypes)
{
if (IsContentType(request, contentType)) return true;
}
return false;
}
/// <summary>
/// Duplicate Params are given a unique key by appending a #1 suffix
/// </summary>
public static Dictionary<string, string> GetRequestParams(this IRequest request)
{
var map = new Dictionary<string, string>();
foreach (var name in request.QueryString.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
var values = request.QueryString.GetValues(name);
if (values.Length == 1)
{
map[name] = values[0];
}
else
{
for (var i = 0; i < values.Length; i++)
{
map[name + (i == 0 ? "" : "#" + i)] = values[i];
}
}
}
if ((request.Verb == HttpMethods.Post || request.Verb == HttpMethods.Put)
&& request.FormData != null)
{
foreach (var name in request.FormData.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
var values = request.FormData.GetValues(name);
if (values.Length == 1)
{
map[name] = values[0];
}
else
{
for (var i = 0; i < values.Length; i++)
{
map[name + (i == 0 ? "" : "#" + i)] = values[i];
}
}
}
}
return map;
}
/// <summary>
/// Duplicate params have their values joined together in a comma-delimited string
/// </summary>
public static Dictionary<string, string> GetFlattenedRequestParams(this IRequest request)
{
var map = new Dictionary<string, string>();
foreach (var name in request.QueryString.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.QueryString[name];
}
if ((request.Verb == HttpMethods.Post || request.Verb == HttpMethods.Put)
&& request.FormData != null)
{
foreach (var name in request.FormData.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.FormData[name];
}
}
return map;
}
public static string GetQueryStringContentType(this IRequest httpReq)
{
var callback = httpReq.QueryString[Keywords.Callback];
if (!string.IsNullOrEmpty(callback)) return MimeTypes.Json;
var format = httpReq.QueryString[Keywords.Format];
if (format == null)
{
const int formatMaxLength = 4;
var pi = httpReq.PathInfo;
if (pi == null || pi.Length <= formatMaxLength) return null;
if (pi[0] == '/') pi = pi.Substring(1);
format = pi.LeftPart('/');
if (format.Length > formatMaxLength) return null;
}
format = format.LeftPart('.').ToLower();
if (format.Contains("json")) return MimeTypes.Json;
if (format.Contains("xml")) return MimeTypes.Xml;
if (format.Contains("jsv")) return MimeTypes.Jsv;
string contentType;
HostContext.ContentTypes.ContentTypeFormats.TryGetValue(format, out contentType);
return contentType;
}
/// <summary>
/// Use this to treat Request.Items[] as a cache by returning pre-computed items to save
/// calculating them multiple times.
/// </summary>
public static object ResolveItem(this IRequest httpReq,
string itemKey, Func<IRequest, object> resolveFn)
{
object cachedItem;
if (httpReq.Items.TryGetValue(itemKey, out cachedItem))
return cachedItem;
var item = resolveFn(httpReq);
httpReq.Items[itemKey] = item;
return item;
}
public static string GetResponseContentType(this IRequest httpReq)
{
var specifiedContentType = GetQueryStringContentType(httpReq);
if (!String.IsNullOrEmpty(specifiedContentType)) return specifiedContentType;
var acceptContentTypes = httpReq.AcceptTypes;
var defaultContentType = httpReq.ContentType;
if (httpReq.HasAnyOfContentTypes(MimeTypes.FormUrlEncoded, MimeTypes.MultiPartFormData))
{
defaultContentType = HostContext.Config.DefaultContentType;
}
var customContentTypes = HostContext.ContentTypes.ContentTypeFormats.Values;
var preferredContentTypes = HostContext.Config.PreferredContentTypesArray;
var acceptsAnything = false;
var hasDefaultContentType = !String.IsNullOrEmpty(defaultContentType);
if (acceptContentTypes != null)
{
var hasPreferredContentTypes = new bool[preferredContentTypes.Length];
foreach (var acceptsType in acceptContentTypes)
{
var contentType = ContentFormat.GetRealContentType(acceptsType);
acceptsAnything = acceptsAnything || contentType == "*/*";
for (var i = 0; i < preferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) continue;
var preferredContentType = preferredContentTypes[i];
hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);
//Prefer Request.ContentType if it is also a preferredContentType
if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
return preferredContentType;
}
}
for (var i = 0; i < preferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) return preferredContentTypes[i];
}
if (acceptsAnything)
{
if (hasDefaultContentType)
return defaultContentType;
if (HostContext.Config.DefaultContentType != null)
return HostContext.Config.DefaultContentType;
}
foreach (var contentType in acceptContentTypes)
{
foreach (var customContentType in customContentTypes)
{
if (contentType.StartsWith(customContentType, StringComparison.OrdinalIgnoreCase))
return customContentType;
}
}
}
if (httpReq.ContentType.MatchesContentType(MimeTypes.Soap12))
{
return MimeTypes.Soap12;
}
if (acceptContentTypes == null && httpReq.ContentType == MimeTypes.Soap11)
{
return MimeTypes.Soap11;
}
//We could also send a '406 Not Acceptable', but this is allowed also
return HostContext.Config.DefaultContentType;
}
public static void SetView(this IRequest httpReq, string viewName)
{
httpReq.SetItem("View", viewName);
}
public static string GetView(this IRequest httpReq)
{
return httpReq.GetItem("View") as string;
}
public static void SetTemplate(this IRequest httpReq, string templateName)
{
httpReq.SetItem("Template", templateName);
}
public static string GetTemplate(this IRequest httpReq)
{
return httpReq.GetItem("Template") as string;
}
public static string ResolveAbsoluteUrl(this IRequest httpReq, string url)
{
return HostContext.ResolveAbsoluteUrl(url, httpReq);
}
public static string ResolveBaseUrl(this IRequest httpReq)
{
return HostContext.ResolveAbsoluteUrl("~/", httpReq);
}
public static string GetAbsoluteUrl(this IRequest httpReq, string url)
{
if (url.SafeSubstring(0, 2) == "~/")
{
url = httpReq.GetBaseUrl().CombineWith(url.Substring(2));
}
return url;
}
public static string InferBaseUrl(this string absoluteUri, string fromPathInfo = null)
{
if (string.IsNullOrEmpty(fromPathInfo))
{
fromPathInfo = "/" + (HostContext.Config.HandlerFactoryPath ?? "");
}
else
{
fromPathInfo = fromPathInfo.TrimEnd('/');
if (fromPathInfo.Length == 0)
return null;
}
if (string.IsNullOrEmpty(absoluteUri))
return null;
var pos = absoluteUri.IndexOf(fromPathInfo, "https://".Length + 1, StringComparison.Ordinal);
return pos >= 0 ? absoluteUri.Substring(0, pos) : absoluteUri;
}
public static string GetBaseUrl(this IRequest httpReq)
{
var baseUrl = HttpHandlerFactory.GetBaseUrl();
if (baseUrl != null)
return baseUrl.NormalizeScheme();
baseUrl = httpReq.AbsoluteUri.InferBaseUrl(fromPathInfo: httpReq.PathInfo);
if (baseUrl != null)
return baseUrl.NormalizeScheme();
var handlerPath = HostContext.Config.HandlerFactoryPath;
return new Uri(httpReq.AbsoluteUri).GetLeftPart(UriPartial.Authority)
.NormalizeScheme()
.CombineWith(handlerPath)
.TrimEnd('/');
}
public static string NormalizeScheme(this string url)
{
if (url == null)
return null;
if (!HostContext.Config.UseHttpsLinks)
return url;
url = url.TrimStart();
if (url.StartsWith("http://"))
return "https://" + url.Substring("http://".Length);
return url;
}
public static RequestAttributes ToRequestAttributes(string[] attrNames)
{
var attrs = RequestAttributes.None;
foreach (var simulatedAttr in attrNames)
{
var attr = (RequestAttributes)Enum.Parse(typeof(RequestAttributes), simulatedAttr, true);
attrs |= attr;
}
return attrs;
}
public static RequestAttributes GetAttributes(this IRequest request)
{
if (HostContext.DebugMode
&& request.QueryString != null) //Mock<IHttpRequest>
{
var simulate = request.QueryString["simulate"];
if (simulate != null)
{
return ToRequestAttributes(simulate.Split(','));
}
}
var portRestrictions = RequestAttributes.None;
portRestrictions |= ContentFormat.GetRequestAttribute(request.Verb);
portRestrictions |= request.IsSecureConnection ? RequestAttributes.Secure : RequestAttributes.InSecure;
if (request.UserHostAddress != null)
{
var isIpv4Address = request.UserHostAddress.IndexOf('.') != -1
&& request.UserHostAddress.IndexOf("::", StringComparison.InvariantCulture) == -1;
string ipAddressNumber = null;
if (isIpv4Address)
{
ipAddressNumber = request.UserHostAddress.LeftPart(":");
}
else
{
if (request.UserHostAddress.Contains("]:"))
{
ipAddressNumber = request.UserHostAddress.LastLeftPart(":");
}
else
{
ipAddressNumber = request.UserHostAddress.LastIndexOf("%", StringComparison.InvariantCulture) > 0 ?
request.UserHostAddress.LastLeftPart(":") :
request.UserHostAddress;
}
}
try
{
ipAddressNumber = ipAddressNumber.LeftPart(',');
var ipAddress = ipAddressNumber.StartsWith("::1")
? IPAddress.IPv6Loopback
: IPAddress.Parse(ipAddressNumber);
portRestrictions |= GetAttributes(ipAddress);
}
catch (Exception ex)
{
throw new ArgumentException("Could not parse Ipv{0} Address: {1} / {2}"
.Fmt((isIpv4Address ? 4 : 6), request.UserHostAddress, ipAddressNumber), ex);
}
}
return portRestrictions;
}
public static RequestAttributes GetAttributes(IPAddress ipAddress)
{
if (IPAddress.IsLoopback(ipAddress))
return RequestAttributes.Localhost;
return IsInLocalSubnet(ipAddress)
? RequestAttributes.LocalSubnet
: RequestAttributes.External;
}
public static bool IsInLocalSubnet(IPAddress ipAddress)
{
var ipAddressBytes = ipAddress.GetAddressBytes();
switch (ipAddress.AddressFamily)
{
case AddressFamily.InterNetwork:
foreach (var localIpv4AddressAndMask in ServiceStackHandlerBase.NetworkInterfaceIpv4Addresses)
{
if (ipAddressBytes.IsInSameIpv4Subnet(localIpv4AddressAndMask.Key, localIpv4AddressAndMask.Value))
{
return true;
}
}
break;
case AddressFamily.InterNetworkV6:
foreach (var localIpv6Address in ServiceStackHandlerBase.NetworkInterfaceIpv6Addresses)
{
if (ipAddressBytes.IsInSameIpv6Subnet(localIpv6Address))
{
return true;
}
}
break;
}
return false;
}
public static HttpContextBase ToHttpContextBase(this HttpRequestBase aspnetHttpReq)
{
return aspnetHttpReq.RequestContext.HttpContext;
}
public static HttpContextBase ToHttpContextBase(this HttpContext httpContext)
{
return httpContext.Request.RequestContext.HttpContext;
}
public static IHttpRequest ToRequest(this HttpContext httpCtx, string operationName = null)
{
if (httpCtx == null)
throw new NotImplementedException(ErrorMessages.OnlyAllowedInAspNetHosts);
return new AspNetRequest(httpCtx.ToHttpContextBase(), operationName);
}
public static IHttpRequest ToRequest(this HttpContextBase httpCtx, string operationName = null)
{
return new AspNetRequest(httpCtx, operationName);
}
public static IHttpRequest ToRequest(this HttpRequestBase httpCtx, string operationName = null)
{
return new AspNetRequest(httpCtx.ToHttpContextBase(), operationName);
}
public static IHttpRequest ToRequest(this HttpListenerContext httpCtxReq, string operationName = null)
{
return ((HttpListenerBase)ServiceStackHost.Instance).CreateRequest(httpCtxReq, operationName);
}
public static IHttpResponse ToResponse(this HttpContext httpCtx)
{
return httpCtx.ToRequest().HttpResponse;
}
public static IHttpResponse ToResponse(this HttpRequestBase aspReq)
{
return aspReq.ToRequest().HttpResponse;
}
public static IHttpResponse ToResponse(this HttpListenerContext httpCtx)
{
return httpCtx.ToRequest().HttpResponse;
}
public static void SetOperationName(this IRequest httpReq, string operationName)
{
if (httpReq.OperationName == null)
{
var aspReq = httpReq as AspNetRequest;