forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHostConfig.cs
More file actions
460 lines (406 loc) · 20.8 KB
/
Copy pathHostConfig.cs
File metadata and controls
460 lines (406 loc) · 20.8 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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Configuration;
using System.Xml;
using System.Xml.Linq;
using MarkdownSharp;
using ServiceStack.Configuration;
using ServiceStack.Host;
using ServiceStack.Logging;
using ServiceStack.Markdown;
using ServiceStack.Metadata;
using ServiceStack.Text;
namespace ServiceStack
{
public class HostConfig
{
public const string DefaultWsdlNamespace = "http://schemas.servicestack.net/types";
public static string ServiceStackPath = null;
private static HostConfig instance;
public static HostConfig Instance
{
get { return instance ?? (instance = NewInstance()); }
}
public static HostConfig ResetInstance()
{
return instance = NewInstance();
}
public static HostConfig NewInstance()
{
var config = new HostConfig
{
WsdlServiceNamespace = DefaultWsdlNamespace,
ApiVersion = "1.0",
EmbeddedResourceSources = new List<Assembly>(),
EmbeddedResourceBaseTypes = new[] { HostContext.AppHost.GetType(), typeof(Service) }.ToList(),
EmbeddedResourceTreatAsFiles = new HashSet<string>(),
LogFactory = new NullLogFactory(),
EnableAccessRestrictions = true,
WebHostPhysicalPath = "~".MapServerPath(),
HandlerFactoryPath = ServiceStackPath,
MetadataRedirectPath = null,
DefaultContentType = null,
PreferredContentTypes = new List<string> {
MimeTypes.Html, MimeTypes.Json, MimeTypes.Xml, MimeTypes.Jsv
},
AllowJsonpRequests = true,
AllowRouteContentTypeExtensions = true,
AllowNonHttpOnlyCookies = false,
UseHttpsLinks = false,
DebugMode = false,
DefaultDocuments = new List<string> {
"default.htm",
"default.html",
"default.cshtml",
"default.md",
"index.htm",
"index.html",
"default.aspx",
"default.ashx",
},
GlobalResponseHeaders = new Dictionary<string, string> {
{ "Vary", "Accept" },
{ "X-Powered-By", Env.ServerUserAgent },
},
IgnoreFormatsInMetadata = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
},
AllowFileExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"js", "ts", "tsx", "jsx", "css", "htm", "html", "shtm", "txt", "xml", "rss", "csv", "pdf",
"jpg", "jpeg", "gif", "png", "bmp", "ico", "tif", "tiff", "svg",
"avi", "divx", "m3u", "mov", "mp3", "mpeg", "mpg", "qt", "vob", "wav", "wma", "wmv",
"flv", "swf", "xap", "xaml", "ogg", "ogv", "mp4", "webm", "eot", "ttf", "woff", "woff2", "map"
},
DebugAspNetHostEnvironment = Env.IsMono ? "FastCGI" : "IIS7",
DebugHttpListenerHostEnvironment = Env.IsMono ? "XSP" : "WebServer20",
EnableFeatures = Feature.All,
WriteErrorsToResponse = true,
ReturnsInnerException = true,
DisposeDependenciesAfterUse = true,
LogUnobservedTaskExceptions = true,
MarkdownOptions = new MarkdownOptions(),
MarkdownBaseType = typeof(MarkdownViewBase),
MarkdownGlobalHelpers = new Dictionary<string, Type>(),
HtmlReplaceTokens = new Dictionary<string, string>(),
AddMaxAgeForStaticMimeTypes = new Dictionary<string, TimeSpan> {
{ "image/gif", TimeSpan.FromHours(1) },
{ "image/png", TimeSpan.FromHours(1) },
{ "image/jpeg", TimeSpan.FromHours(1) },
},
AppendUtf8CharsetOnContentTypes = new HashSet<string> { MimeTypes.Json, },
RouteNamingConventions = new List<RouteNamingConventionDelegate> {
RouteNamingConvention.WithRequestDtoName,
RouteNamingConvention.WithMatchingAttributes,
RouteNamingConvention.WithMatchingPropertyNames
},
MapExceptionToStatusCode = new Dictionary<Type, int>(),
OnlySendSessionCookiesSecurely = false,
AllowSessionIdsInHttpParams = false,
AllowSessionCookies = true,
RestrictAllCookiesToDomain = null,
DefaultJsonpCacheExpiration = new TimeSpan(0, 20, 0),
MetadataVisibility = RequestAttributes.Any,
Return204NoContentForEmptyResponse = true,
AllowJsConfig = true,
AllowPartialResponses = true,
AllowAclUrlReservation = true,
AddRedirectParamsToQueryString = false,
RedirectToDefaultDocuments = false,
StripApplicationVirtualPath = false,
ScanSkipPaths = new List<string> {
"obj/",
"bin/",
"node_modules/",
"jspm_packages/",
"bower_components/",
"wwwroot/",
"wwwroot_build/",
},
IgnoreWarningsOnPropertyNames = new List<string> {
Keywords.Format, Keywords.Callback, Keywords.Debug, Keywords.AuthSecret,
Keywords.IgnorePlaceHolder, Keywords.Version, Keywords.VersionAbbr, Keywords.Version.ToPascalCase(),
},
XmlWriterSettings = new XmlWriterSettings
{
Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
},
FallbackRestPath = null,
};
if (config.HandlerFactoryPath == null)
{
config.InferHttpHandlerPath();
}
return config;
}
public HostConfig()
{
if (instance == null) return;
//Get a copy of the singleton already partially configured
this.WsdlServiceNamespace = instance.WsdlServiceNamespace;
this.ApiVersion = instance.ApiVersion;
this.EmbeddedResourceSources = instance.EmbeddedResourceSources;
this.EmbeddedResourceBaseTypes = instance.EmbeddedResourceBaseTypes;
this.EmbeddedResourceTreatAsFiles = instance.EmbeddedResourceTreatAsFiles;
this.EnableAccessRestrictions = instance.EnableAccessRestrictions;
this.ServiceEndpointsMetadataConfig = instance.ServiceEndpointsMetadataConfig;
this.SoapServiceName = instance.SoapServiceName;
this.XmlWriterSettings = instance.XmlWriterSettings;
this.LogFactory = instance.LogFactory;
this.EnableAccessRestrictions = instance.EnableAccessRestrictions;
this.WebHostUrl = instance.WebHostUrl;
this.WebHostPhysicalPath = instance.WebHostPhysicalPath;
this.DefaultRedirectPath = instance.DefaultRedirectPath;
this.MetadataRedirectPath = instance.MetadataRedirectPath;
this.HandlerFactoryPath = instance.HandlerFactoryPath;
this.DefaultContentType = instance.DefaultContentType;
this.PreferredContentTypes = instance.PreferredContentTypes;
this.AllowJsonpRequests = instance.AllowJsonpRequests;
this.AllowRouteContentTypeExtensions = instance.AllowRouteContentTypeExtensions;
this.DebugMode = instance.DebugMode;
this.DefaultDocuments = instance.DefaultDocuments;
this.GlobalResponseHeaders = instance.GlobalResponseHeaders;
this.IgnoreFormatsInMetadata = instance.IgnoreFormatsInMetadata;
this.AllowFileExtensions = instance.AllowFileExtensions;
this.EnableFeatures = instance.EnableFeatures;
this.WriteErrorsToResponse = instance.WriteErrorsToResponse;
this.DisposeDependenciesAfterUse = instance.DisposeDependenciesAfterUse;
this.LogUnobservedTaskExceptions = instance.LogUnobservedTaskExceptions;
this.ReturnsInnerException = instance.ReturnsInnerException;
this.MarkdownOptions = instance.MarkdownOptions;
this.MarkdownBaseType = instance.MarkdownBaseType;
this.MarkdownGlobalHelpers = instance.MarkdownGlobalHelpers;
this.HtmlReplaceTokens = instance.HtmlReplaceTokens;
this.AddMaxAgeForStaticMimeTypes = instance.AddMaxAgeForStaticMimeTypes;
this.AppendUtf8CharsetOnContentTypes = instance.AppendUtf8CharsetOnContentTypes;
this.RouteNamingConventions = instance.RouteNamingConventions;
this.MapExceptionToStatusCode = instance.MapExceptionToStatusCode;
this.OnlySendSessionCookiesSecurely = instance.OnlySendSessionCookiesSecurely;
this.AllowSessionIdsInHttpParams = instance.AllowSessionIdsInHttpParams;
this.AllowSessionCookies = instance.AllowSessionCookies;
this.RestrictAllCookiesToDomain = instance.RestrictAllCookiesToDomain;
this.DefaultJsonpCacheExpiration = instance.DefaultJsonpCacheExpiration;
this.MetadataVisibility = instance.MetadataVisibility;
this.Return204NoContentForEmptyResponse = instance.Return204NoContentForEmptyResponse;
this.AllowNonHttpOnlyCookies = instance.AllowNonHttpOnlyCookies;
this.AllowJsConfig = instance.AllowJsConfig;
this.AllowPartialResponses = instance.AllowPartialResponses;
this.IgnoreWarningsOnPropertyNames = instance.IgnoreWarningsOnPropertyNames;
this.FallbackRestPath = instance.FallbackRestPath;
this.AllowAclUrlReservation = instance.AllowAclUrlReservation;
this.AddRedirectParamsToQueryString = instance.AddRedirectParamsToQueryString;
this.RedirectToDefaultDocuments = instance.RedirectToDefaultDocuments;
this.StripApplicationVirtualPath = instance.StripApplicationVirtualPath;
this.SkipFormDataInCreatingRequest = instance.SkipFormDataInCreatingRequest;
this.ScanSkipPaths = instance.ScanSkipPaths;
this.AdminAuthSecret = instance.AdminAuthSecret;
}
public string WsdlServiceNamespace { get; set; }
public string ApiVersion { get; set; }
private RequestAttributes metadataVisibility;
public RequestAttributes MetadataVisibility
{
get { return metadataVisibility; }
set { metadataVisibility = value.ToAllowedFlagsSet(); }
}
public List<Type> EmbeddedResourceBaseTypes { get; set; }
public List<Assembly> EmbeddedResourceSources { get; set; }
public HashSet<string> EmbeddedResourceTreatAsFiles { get; set; }
public string DefaultContentType { get; set; }
public List<string> PreferredContentTypes { get; set; }
internal string[] PreferredContentTypesArray = TypeConstants.EmptyStringArray; //use array at runtime
public bool AllowJsonpRequests { get; set; }
public bool AllowRouteContentTypeExtensions { get; set; }
public bool DebugMode { get; set; }
public string DebugAspNetHostEnvironment { get; set; }
public string DebugHttpListenerHostEnvironment { get; set; }
public List<string> DefaultDocuments { get; private set; }
public List<string> IgnoreWarningsOnPropertyNames { get; private set; }
public HashSet<string> IgnoreFormatsInMetadata { get; set; }
public HashSet<string> AllowFileExtensions { get; set; }
public string WebHostUrl { get; set; }
public string WebHostPhysicalPath { get; set; }
public string HandlerFactoryPath { get; set; }
public string DefaultRedirectPath { get; set; }
public string MetadataRedirectPath { get; set; }
public ServiceEndpointsMetadataConfig ServiceEndpointsMetadataConfig { get; set; }
public string SoapServiceName { get; set; }
public XmlWriterSettings XmlWriterSettings { get; set; }
public ILogFactory LogFactory { get; set; }
public bool EnableAccessRestrictions { get; set; }
public bool UseBclJsonSerializers { get; set; }
public Dictionary<string, string> GlobalResponseHeaders { get; set; }
public Feature EnableFeatures { get; set; }
public bool ReturnsInnerException { get; set; }
public bool WriteErrorsToResponse { get; set; }
public bool DisposeDependenciesAfterUse { get; set; }
public bool LogUnobservedTaskExceptions { get; set; }
public MarkdownOptions MarkdownOptions { get; set; }
public Type MarkdownBaseType { get; set; }
public Dictionary<string, Type> MarkdownGlobalHelpers { get; set; }
public Dictionary<string, string> HtmlReplaceTokens { get; set; }
public HashSet<string> AppendUtf8CharsetOnContentTypes { get; set; }
public Dictionary<string, TimeSpan> AddMaxAgeForStaticMimeTypes { get; set; }
public List<RouteNamingConventionDelegate> RouteNamingConventions { get; set; }
public Dictionary<Type, int> MapExceptionToStatusCode { get; set; }
public bool OnlySendSessionCookiesSecurely { get; set; }
public bool AllowSessionIdsInHttpParams { get; set; }
public bool AllowSessionCookies { get; set; }
public string RestrictAllCookiesToDomain { get; set; }
public TimeSpan DefaultJsonpCacheExpiration { get; set; }
public bool Return204NoContentForEmptyResponse { get; set; }
public bool AllowJsConfig { get; set; }
public bool AllowPartialResponses { get; set; }
public bool AllowNonHttpOnlyCookies { get; set; }
public bool AllowAclUrlReservation { get; set; }
public bool AddRedirectParamsToQueryString { get; set; }
public bool RedirectToDefaultDocuments { get; set; }
public bool StripApplicationVirtualPath { get; set; }
public bool SkipFormDataInCreatingRequest { get; set; }
//Skip scanning common VS.NET extensions
public List<string> ScanSkipPaths { get; private set; }
public bool UseHttpsLinks { get; set; }
public string AdminAuthSecret { get; set; }
public FallbackRestPathDelegate FallbackRestPath { get; set; }
const string NamespacesAppSettingsKey = "servicestack.razor.namespaces";
private HashSet<string> razorNamespaces;
public HashSet<string> RazorNamespaces
{
get
{
if (razorNamespaces != null)
return razorNamespaces;
razorNamespaces = new HashSet<string>();
//Infer from <system.web.webPages.razor> - what VS.NET's intell-sense uses
var configPath = HostContext.GetAppConfigPath();
if (configPath != null)
{
var xml = configPath.ReadAllText();
var doc = XElement.Parse(xml);
doc.AnyElement("system.web.webPages.razor")
.AnyElement("pages")
.AnyElement("namespaces")
.AllElements("add").ToList()
.ForEach(x => razorNamespaces.Add(x.AnyAttribute("namespace").Value));
}
//E.g. <add key="servicestack.razor.namespaces" value="System,ServiceStack.Text" />
if (ConfigUtils.GetNullableAppSetting(NamespacesAppSettingsKey) != null)
{
ConfigUtils.GetListFromAppSetting(NamespacesAppSettingsKey)
.ForEach(x => razorNamespaces.Add(x));
}
//log.Debug("Loaded Razor Namespaces: in {0}: {1}: {2}"
// .Fmt(configPath, "~/Web.config".MapHostAbsolutePath(), razorNamespaces.Dump()));
return razorNamespaces;
}
}
private System.Configuration.Configuration GetAppConfig()
{
Assembly entryAssembly;
//Read the user-defined path in the Web.Config
if (HostContext.IsAspNetHost)
return WebConfigurationManager.OpenWebConfiguration("~/");
if ((entryAssembly = Assembly.GetEntryAssembly()) != null)
return ConfigurationManager.OpenExeConfiguration(entryAssembly.Location);
return null;
}
private void InferHttpHandlerPath()
{
try
{
var config = GetAppConfig();
if (config == null) return;
SetPathsFromConfiguration(config, null);
if (MetadataRedirectPath == null)
{
foreach (ConfigurationLocation location in config.Locations)
{
SetPathsFromConfiguration(location.OpenConfiguration(), (location.Path ?? "").ToLower());
if (MetadataRedirectPath != null) { break; }
}
}
if (HostContext.IsAspNetHost && MetadataRedirectPath == null)
{
throw new ConfigurationErrorsException(
"Unable to infer ServiceStack's <httpHandler.Path/> from the Web.Config\n"
+ "Check with https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice to ensure you have configured ServiceStack properly.\n"
+ "Otherwise you can explicitly set your httpHandler.Path by setting: EndpointHostConfig.ServiceStackPath");
}
}
catch (Exception) { }
}
private void SetPathsFromConfiguration(System.Configuration.Configuration config, string locationPath)
{
if (config == null)
return;
//standard config
var handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection;
if (handlersSection != null)
{
for (var i = 0; i < handlersSection.Handlers.Count; i++)
{
var httpHandler = handlersSection.Handlers[i];
if (!httpHandler.Type.StartsWith("ServiceStack"))
continue;
SetPaths(httpHandler.Path, locationPath);
break;
}
}
//IIS7+ integrated mode system.webServer/handlers
var pathsNotSet = MetadataRedirectPath == null;
if (pathsNotSet)
{
var webServerSection = config.GetSection("system.webServer");
if (webServerSection != null)
{
var rawXml = webServerSection.SectionInformation.GetRawXml();
if (!String.IsNullOrEmpty(rawXml))
{
SetPaths(ExtractHandlerPathFromWebServerConfigurationXml(rawXml), locationPath);
}
}
//In some MVC Hosts auto-inferencing doesn't work, in these cases assume the most likely default of "/api" path
pathsNotSet = MetadataRedirectPath == null;
if (pathsNotSet)
{
var isMvcHost = Type.GetType("System.Web.Mvc.Controller") != null;
if (isMvcHost)
{
SetPaths("api", null);
}
}
}
}
private void SetPaths(string handlerPath, string locationPath)
{
if (handlerPath == null) return;
if (locationPath == null)
{
handlerPath = handlerPath.Replace("*", String.Empty);
}
HandlerFactoryPath = locationPath ??
(String.IsNullOrEmpty(handlerPath) ? null : handlerPath);
MetadataRedirectPath = "metadata";
}
private static string ExtractHandlerPathFromWebServerConfigurationXml(string rawXml)
{
return XDocument.Parse(rawXml).Root.Element("handlers")
.Descendants("add")
.Where(handler => EnsureHandlerTypeAttribute(handler).StartsWith("ServiceStack"))
.Select(handler => handler.Attribute("path").Value)
.FirstOrDefault();
}
private static string EnsureHandlerTypeAttribute(XElement handler)
{
if (handler.Attribute("type") != null && !String.IsNullOrEmpty(handler.Attribute("type").Value))
{
return handler.Attribute("type").Value;
}
return String.Empty;
}
}
}