/
ServiceStackHost.cs
2151 lines (1811 loc) · 75.9 KB
/
ServiceStackHost.cs
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
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
#if !NETCORE
using System.Web;
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Funq;
using Microsoft.Extensions.DependencyInjection;
using ServiceStack.Admin;
using ServiceStack.Auth;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Formats;
using ServiceStack.Host;
using ServiceStack.Host.Handlers;
using ServiceStack.Html;
using ServiceStack.IO;
using ServiceStack.Logging;
using ServiceStack.Messaging;
using ServiceStack.Metadata;
using ServiceStack.NativeTypes;
using ServiceStack.Serialization;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
using ServiceStack.Web;
using ServiceStack.Redis;
using ServiceStack.Script;
namespace ServiceStack;
public abstract partial class ServiceStackHost
: IAppHost, IFunqlet, IHasContainer, IDisposable
{
protected ILog Log = LogManager.GetLogger(typeof(ServiceStackHost));
public bool IsDebugLogEnabled => Log.IsDebugEnabled;
/// <summary>
/// Singleton access to AppHost
/// </summary>
public static ServiceStackHost Instance { get; protected set; }
/// <summary>
/// When the AppHost was instantiated.
/// </summary>
public DateTime StartedAt { get; set; }
/// <summary>
/// When the Init function was done.
/// Called at begin of <see cref="OnAfterInit"/>
/// </summary>
public DateTime? AfterInitAt { get; set; }
/// <summary>
/// When all configuration was completed.
/// Called at the end of <see cref="OnAfterInit"/>
/// </summary>
public DateTime? ReadyAt { get; set; }
/// <summary>
/// If app currently runs for unit tests.
/// Used for overwriting AuthSession.
/// </summary>
public bool TestMode { get; set; }
/// <summary>
/// Whether to add Timestamp to Request
/// </summary>
public bool AddTimings { get; set; }
/// <summary>
/// The base path ServiceStack is hosted on
/// </summary>
public virtual string PathBase
{
get => Config?.HandlerFactoryPath;
set => Config.HandlerFactoryPath = value;
}
/// <summary>
/// The assemblies reflected to find api services.
/// These can be provided in the constructor call.
/// </summary>
public List<Assembly> ServiceAssemblies { get; }
/// <summary>
/// Whether AppHost has been already initialized
/// </summary>
public static bool HasInit => Instance != null;
/// <summary>
/// Whether AppHost configuration is done.
/// Note: It doesn't mean the start function was called.
/// </summary>
public bool HasStarted => ReadyAt != null;
/// <summary>
/// Whether AppHost is ready configured and either ready to run or already running.
/// Equals <see cref="HasStarted"/>
/// </summary>
public static bool IsReady() => Instance?.ReadyAt != null;
/// <summary>
/// Sharp App Name
/// </summary>
public string AppName { get; set; }
/// <summary>
/// Init Options before AppHost is initialized, e.g. in services.AddServiceStack(asm, options => { ... })
/// </summary>
public static ServiceStackServicesOptions InitOptions { get; internal set; } = new();
protected ServiceStackHost(string serviceName, params Assembly[] assembliesWithServices)
{
this.StartedAt = DateTime.UtcNow;
ServiceName = serviceName;
ServiceAssemblies = InitOptions.ServiceAssemblies;
ServiceAssemblies.AddDistinctRange(assembliesWithServices);
Plugins = InitOptions.Plugins;
RestPaths = InitOptions.Routes;
OnPreRegisterPlugins = InitOptions.OnPreRegisterPlugins;
OnPostRegisterPlugins = InitOptions.OnPostRegisterPlugins;
ContentTypes = new ContentTypes();
Routes = new ServiceRoutes(this);
Metadata = new ServiceMetadata(RestPaths);
RawHttpHandlers = [
ReturnRedirectHandler,
ReturnRequestInfoHandler
];
DefaultScriptContext = InitOptions.ScriptContext;
DefaultScriptContext.Container = Container;
JsConfig.InitStatics();
}
/// <summary>
/// Configure your AppHost and its dependencies
/// </summary>
public abstract void Configure(Container container);
protected virtual ServiceController CreateServiceController(params Assembly[] assembliesWithServices)
{
if (assembliesWithServices == null || assembliesWithServices.Length == 0)
throw new ArgumentException(
"No Assemblies provided in your AppHost's base constructor.\n"
+ "To register your services, please provide the assemblies where your web services are defined.");
var serviceTypes = GetAssemblyServiceTypes(assembliesWithServices);
serviceTypes.AddDistinctRange(InitOptions.ServiceTypes);
InitOptions.ServiceTypes.Clear();
return CreateServiceController(serviceTypes);
}
protected List<Type> GetAssemblyServiceTypes(Assembly[] assembliesWithServices)
{
var results = new List<Type>();
string assemblyName = null;
string typeName = null;
try
{
foreach (var assembly in assembliesWithServices)
{
assemblyName = assembly.FullName;
foreach (var type in assembly.GetTypes().Where(ServiceController.IsServiceType))
{
if (ExcludeAutoRegisteringServiceTypes.Contains(type))
continue;
typeName = type.GetOperationName();
results.Add(type);
}
}
return results;
}
catch (Exception ex)
{
var msg = $"Failed loading types, last assembly '{assemblyName}', type: '{typeName}'";
LogManager.GetLogger(GetType()).Error(msg, ex);
throw new Exception(msg, ex);
}
}
protected virtual ServiceController CreateServiceController(IEnumerable<Type> serviceTypes)
{
return new(this, () => serviceTypes);
}
/// <summary>
/// Set the host config of the AppHost.
/// </summary>
public virtual void SetConfig(HostConfig config)
{
Config = config;
}
/// <summary>
/// Initializes the AppHost.
/// Calls the <see cref="Configure"/> method.
/// Should be called before start.
/// </summary>
public virtual ServiceStackHost Init()
{
if (HasInit)
throw new InvalidDataException($"ServiceStackHost.Instance has already been set ({Instance.GetType().Name})");
Service.GlobalResolver = Instance = this;
RegisterLicenseKey(AppSettings.GetNullableString("servicestack:license"));
var scanAssemblies = new List<Assembly>(ServiceAssemblies);
scanAssemblies.AddIfNotExists(GetType().Assembly);
var scanTypes = scanAssemblies.SelectMany(x => x.GetTypes())
.Where(x => !(x.IsInterface || x.IsAbstract || x.IsGenericTypeDefinition)
&& (x.HasInterface(typeof(IPreConfigureAppHost))
|| x.HasInterface(typeof(IConfigureAppHost))
|| x.HasInterface(typeof(IAfterInitAppHost))))
.ToArray();
var startupConfigs = scanTypes.Where(x => !x.HasInterface(typeof(IPlugin)))
.Select(x => x.CreateInstance()).WithPriority();
var configInstances = startupConfigs.PriorityOrdered();
var preStartupConfigs = startupConfigs.PriorityBelowZero();
var postStartupConfigs = startupConfigs.PriorityZeroOrAbove();
void RunPreConfigure(object instance)
{
try
{
if (instance is IPreConfigureAppHost preConfigureAppHost)
preConfigureAppHost.PreConfigure(this);
}
catch (Exception ex)
{
OnStartupException(ex, instance.GetType().Name, nameof(RunPreConfigure));
}
}
var priorityPlugins = Plugins.WithPriority().PriorityOrdered().Map(x => (IPlugin)x);
priorityPlugins.ForEach(RunPreConfigure);
configInstances.ForEach(RunPreConfigure);
ServiceController ??= CreateServiceController(ServiceAssemblies.ToArray());
RpcGateway = new RpcGateway(this);
Config = HostConfig.ResetInstance();
OnConfigLoad();
AbstractVirtualFileBase.ScanSkipPaths = Config.ScanSkipPaths;
ResourceVirtualDirectory.EmbeddedResourceTreatAsFiles = Config.EmbeddedResourceTreatAsFiles;
OnBeforeInit();
ServiceController.Init();
void RunConfigure(object instance)
{
try
{
if (instance is IConfigureAppHost configureAppHost)
configureAppHost.Configure(this);
}
catch (Exception ex)
{
OnStartupException(ex, instance.GetType().Name, nameof(RunConfigure));
}
}
GlobalAfterConfigureServices.ForEach(fn => fn(Container));
GlobalAfterConfigureServices.Clear();
GlobalBeforeConfigure.Each(RunManagedAction);
preStartupConfigs.ForEach(RunConfigure);
BeforeConfigure.Each(RunManagedAction);
Configure(Container);
ConfigureLogging();
AfterConfigure.Each(RunManagedAction);
postStartupConfigs.ForEach(RunConfigure);
GlobalAfterConfigure.Each(RunManagedAction);
if (Config.StrictMode == null && Config.DebugMode)
Config.StrictMode = true;
if (!Config.DebugMode)
Plugins.RemoveAll(x => x is RequestInfoFeature);
var validationPluginsCount = Plugins.Count(x => x is Validation.ValidationFeature);
if (validationPluginsCount > 1)
{
Log.Warn($"Multiple ValidationFeature Plugins detected. Removing default ValidationFeature plugin...");
for (var i = 0; i < Plugins.Count; i++)
{
var plugin = Plugins[i];
if (plugin is Validation.ValidationFeature)
{
Plugins.RemoveAt(i);
break;
}
}
}
//Some plugins need to initialize before other plugins are registered.
Plugins.ToList().ForEach(RunPreInitPlugin);
configInstances.ForEach(RunPreInitPlugin);
List<IVirtualPathProvider> pathProviders = null;
if (VirtualFileSources == null)
{
pathProviders = GetVirtualFileSources().Where(x => x != null).ToList();
VirtualFileSources = pathProviders.Count > 1
? new MultiVirtualFiles(pathProviders.ToArray())
: pathProviders.First();
}
VirtualFiles ??= Container.TryResolve<IVirtualFiles>()
?? pathProviders?.FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles
?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles;
OnAfterInit();
configInstances.ForEach(RunPostInitPlugin);
GlobalAfterPluginsLoaded.Each(RunManagedAction);
PopulateArrayFilters();
LogInitComplete();
HttpHandlerFactory.Init();
foreach (var callback in AfterInitCallbacks)
{
callback(this);
}
Plugins.ForEach(RunAfterInitAppHost);
configInstances.ForEach(RunAfterInitAppHost);
GlobalAfterAppHostInit.Each(RunManagedAction);
ReadyAt = DateTime.UtcNow;
OnReady();
return this;
}
protected virtual void OnReady() {}
public virtual void ConfigureLogging()
{
Log = LogManager.GetLogger(typeof(ServiceStackHost));
}
protected virtual void RegisterLicenseKey(string licenseKeyText)
{
if (!string.IsNullOrEmpty(licenseKeyText))
{
Licensing.RegisterLicense(licenseKeyText);
}
}
protected void PopulateArrayFilters()
{
PreRequestFiltersArray = PreRequestFilters.ToArray();
RequestConvertersArray = RequestConverters.ToArray();
ResponseConvertersArray = ResponseConverters.ToArray();
GlobalRequestFiltersArray = GlobalRequestFilters.ToArray();
GlobalRequestFiltersAsyncArray = GlobalRequestFiltersAsync.ToArray();
GlobalResponseFiltersArray = GlobalResponseFilters.ToArray();
GlobalResponseFiltersAsyncArray = GlobalResponseFiltersAsync.ToArray();
GlobalMessageRequestFiltersArray = GlobalMessageRequestFilters.ToArray();
GlobalMessageRequestFiltersAsyncArray = GlobalMessageRequestFiltersAsync.ToArray();
GlobalMessageResponseFiltersArray = GlobalMessageResponseFilters.ToArray();
GlobalMessageResponseFiltersAsyncArray = GlobalMessageResponseFiltersAsync.ToArray();
RawHttpHandlersArray = RawHttpHandlers.ToArray();
CatchAllHandlersArray = CatchAllHandlers.ToArray();
FallbackHandlersArray = FallbackHandlers.ToArray();
GatewayRequestFiltersArray = GatewayRequestFilters.ToArray();
GatewayRequestFiltersAsyncArray = GatewayRequestFiltersAsync.ToArray();
GatewayResponseFiltersArray = GatewayResponseFilters.ToArray();
GatewayResponseFiltersAsyncArray = GatewayResponseFiltersAsync.ToArray();
}
private void LogInitComplete()
{
var elapsed = DateTime.UtcNow - StartedAt;
var hasErrors = StartUpErrors.Any();
if (hasErrors)
{
Log.ErrorFormat(
"Initializing Application {0} took {1}ms. {2} error(s) detected: {3}",
ServiceName,
elapsed.TotalMilliseconds,
StartUpErrors.Count,
StartUpErrors.ToJson());
Config.GlobalResponseHeaders["X-Startup-Errors"] = StartUpErrors.Count.ToString();
}
else
{
Log.InfoFormat(
"Initializing Application {0} took {1}ms. No errors detected.",
ServiceName,
elapsed.TotalMilliseconds);
}
}
/// <summary>
/// Gets Full Directory Path of where the app is running
/// </summary>
public virtual string GetWebRootPath() => Config.WebHostPhysicalPath;
/// <summary>
/// Override to intercept VFS Providers registered for this AppHost
/// </summary>
public virtual List<IVirtualPathProvider> GetVirtualFileSources()
{
var pathProviders = new List<IVirtualPathProvider>(InsertVirtualFileSources ?? TypeConstants<IVirtualPathProvider>.EmptyList) {
new FileSystemVirtualFiles(GetWebRootPath())
};
pathProviders.AddRange(Config.EmbeddedResourceBaseTypes.Distinct()
.Map(x => new ResourceVirtualFiles(x)));
pathProviders.AddRange(Config.EmbeddedResourceSources.Distinct()
.Map(x => new ResourceVirtualFiles(x)));
if (AddVirtualFileSources.Count > 0)
pathProviders.AddRange(AddVirtualFileSources);
return pathProviders;
}
public virtual T GetVirtualFileSource<T>() where T : class => AfterInitAt != null
? VirtualFileSources.GetVirtualFileSource<T>()
: GetVirtualFileSources().FirstOrDefault(x => x is T) as T;
/// <summary>
/// Starts the AppHost.
/// this methods needs to be overwritten in subclass to provider a listener to start handling requests.
/// </summary>
/// <param name="urlBase">Url to listen to</param>
public virtual ServiceStackHost Start(string urlBase)
{
throw new NotImplementedException("Start(listeningAtUrlBase) is not supported by this AppHost");
}
/// <summary>
/// The public name of this App
/// </summary>
public string ServiceName { get; set; }
/// <summary>
/// ServiceStack's Configuration API, see: https://docs.servicestack.net/appsettings
/// </summary>
public IAppSettings AppSettings { get; set; } = new AppSettings();
/// <summary>
/// The populated Metadata for this AppHost's Services
/// </summary>
public ServiceMetadata Metadata { get; set; }
/// <summary>
/// The ServiceController that executes Services
/// </summary>
public ServiceController ServiceController { get; set; }
/// <summary>
/// Provides a pure object model for executing the full HTTP Request pipeline which returns the Response DTO
/// back to ASP .NET Core gRPC which handles sending the response back to the HTTP/2 connected client.
/// </summary>
public RpcGateway RpcGateway { get; set; }
// Rare for a user to auto register all available services in ServiceStack.dll
// But happens when ILMerged, so exclude auto-registering SS services by default
// and let them register them manually
public HashSet<Type> ExcludeAutoRegisteringServiceTypes { get; set; } =
[
typeof(AuthenticateService),
typeof(RegisterService),
typeof(AssignRolesService),
typeof(UnAssignRolesService),
typeof(NativeTypesService),
typeof(PostmanService),
typeof(HotReloadPageService),
typeof(HotReloadFilesService),
typeof(SpaFallbackService),
typeof(SharpApiService),
typeof(MetadataDebugService),
typeof(ServerEventsSubscribersService),
typeof(ServerEventsUnRegisterService),
typeof(MetadataAppService),
typeof(MetadataNavService),
typeof(ScriptAdminService),
typeof(RequestLogsService),
typeof(AutoQueryMetadataService),
typeof(GetApiKeysService),
typeof(RegenerateApiKeysService),
typeof(ConvertSessionToTokenService),
typeof(GetAccessTokenService),
typeof(StoreFileUploadService),
typeof(ReplaceFileUploadService),
typeof(GetFileUploadService),
typeof(DeleteFileUploadService),
typeof(AdminDashboardService),
typeof(AdminUsersService),
typeof(AdminProfilingService),
typeof(AdminRedisService),
typeof(Validation.GetValidationRulesService),
typeof(Validation.ModifyValidationRulesService)
];
/// <summary>
/// The AppHost.Container. Note: it is not thread safe to register dependencies after AppStart.
/// </summary>
public Container Container { get; protected set; } = new() { DefaultOwner = Owner.External };
/// <summary>
/// Dynamically register Service Routes
/// </summary>
public IServiceRoutes Routes { get; set; }
/// <summary>
/// Registered Routes
/// </summary>
public List<RestPath> RestPaths { get; set; } = [];
/// <summary>
/// Register custom Request Binder
/// </summary>
public Dictionary<Type, Func<IRequest, object>> RequestBinders => ServiceController.RequestTypeFactoryMap;
/// <summary>
/// Manage registered Content Types & their sync/async serializers supported by this AppHost
/// </summary>
public IContentTypes ContentTypes { get; set; }
/// <summary>
/// Collection of PreRequest filters.
/// They are called before each request is handled by a service, but after an HttpHandler is by the <see cref="HttpHandlerFactory"/> chosen.
/// called in <see cref="ApplyPreRequestFilters"/>.
/// </summary>
public List<Action<IRequest, IResponse>> PreRequestFilters { get; set; } = [];
internal Action<IRequest, IResponse>[] PreRequestFiltersArray;
/// <summary>
/// Collection of RequestConverters.
/// Can be used to convert/change Input Dto
/// Called after routing and model binding, but before request filters.
/// All request converters are called unless <see cref="IResponse.IsClosed"></see>
/// Converter can return null, original model will be used.
///
/// Note one converter could influence the input for the next converter!
/// </summary>
public List<Func<IRequest, object, Task<object>>> RequestConverters { get; set; } = [];
internal Func<IRequest, object, Task<object>>[] RequestConvertersArray;
/// <summary>
/// Collection of ResponseConverters.
/// Can be used to convert/change Output Dto
///
/// Called directly after response is handled, even before <see cref="ApplyResponseFiltersAsync"></see>!
/// </summary>
public List<Func<IRequest, object, Task<object>>> ResponseConverters { get; set; } = [];
internal Func<IRequest, object, Task<object>>[] ResponseConvertersArray;
public List<Action<IRequest, IResponse, object>> GlobalRequestFilters { get; set; } = [];
internal Action<IRequest, IResponse, object>[] GlobalRequestFiltersArray;
public List<Func<IRequest, IResponse, object, Task>> GlobalRequestFiltersAsync { get; set; } = [];
internal Func<IRequest, IResponse, object, Task>[] GlobalRequestFiltersAsyncArray;
public Dictionary<Type, ITypedFilter> GlobalTypedRequestFilters { get; set; } = new();
public Dictionary<Type, ITypedFilterAsync> GlobalTypedRequestFiltersAsync { get; set; } = new();
public List<Action<IRequest, IResponse, object>> GlobalResponseFilters { get; set; } = [];
internal Action<IRequest, IResponse, object>[] GlobalResponseFiltersArray;
public List<Func<IRequest, IResponse, object, Task>> GlobalResponseFiltersAsync { get; set; } = [];
internal Func<IRequest, IResponse, object, Task>[] GlobalResponseFiltersAsyncArray;
public Dictionary<Type, ITypedFilter> GlobalTypedResponseFilters { get; set; } = new();
public Dictionary<Type, ITypedFilterAsync> GlobalTypedResponseFiltersAsync { get; set; } = new();
public List<Action<IRequest, IResponse, object>> GlobalMessageRequestFilters { get; } = [];
internal Action<IRequest, IResponse, object>[] GlobalMessageRequestFiltersArray;
public List<Func<IRequest, IResponse, object, Task>> GlobalMessageRequestFiltersAsync { get; } = [];
internal Func<IRequest, IResponse, object, Task>[] GlobalMessageRequestFiltersAsyncArray;
public Dictionary<Type, ITypedFilter> GlobalTypedMessageRequestFilters { get; set; } = new();
public List<Action<IRequest, IResponse, object>> GlobalMessageResponseFilters { get; } = [];
internal Action<IRequest, IResponse, object>[] GlobalMessageResponseFiltersArray;
public List<Func<IRequest, IResponse, object, Task>> GlobalMessageResponseFiltersAsync { get; } = [];
internal Func<IRequest, IResponse, object, Task>[] GlobalMessageResponseFiltersAsyncArray;
public Dictionary<Type, ITypedFilter> GlobalTypedMessageResponseFilters { get; set; } = new();
/// <summary>
/// Lists of view engines for this app.
/// If view is needed list is looped until view is found.
/// </summary>
public List<IViewEngine> ViewEngines { get; set; } = [];
public List<HandleServiceExceptionDelegate> ServiceExceptionHandlers { get; set; } = [];
public List<HandleServiceExceptionAsyncDelegate> ServiceExceptionHandlersAsync { get; set; } = [];
public List<HandleUncaughtExceptionDelegate> UncaughtExceptionHandlers { get; set; } = [];
public List<HandleUncaughtExceptionAsyncDelegate> UncaughtExceptionHandlersAsync { get; set; } = [];
public List<HandleGatewayExceptionDelegate> GatewayExceptionHandlers { get; set; } = [];
public List<HandleGatewayExceptionAsyncDelegate> GatewayExceptionHandlersAsync { get; set; } = [];
/// <summary>
/// Register static callbacks for configuring dependencies
/// </summary>
public static List<Action<IServiceCollection>> GlobalAfterConfigureServices { get; } = [];
/// <summary>
/// Register static callbacks fired just before AppHost.Configure()
/// </summary>
public static List<Action<ServiceStackHost>> GlobalBeforeConfigure { get; } = new();
/// <summary>
/// Register callbacks fired just before AppHost.Configure()
/// </summary>
public List<Action<ServiceStackHost>> BeforeConfigure { get; set; } = [];
/// <summary>
/// Register static callbacks fired just after AppHost.Configure()
/// </summary>
public static List<Action<ServiceStackHost>> GlobalAfterConfigure { get; } = new();
/// <summary>
/// Register callbacks fired just after AppHost.Configure()
/// </summary>
public List<Action<ServiceStackHost>> AfterConfigure { get; set; } = [];
/// <summary>
/// Register static callbacks fired just after plugins are loaded
/// </summary>
public static List<Action<ServiceStackHost>> GlobalAfterPluginsLoaded { get; } = new();
/// <summary>
/// Register callbacks fired just after plugins are loaded
/// </summary>
public List<Action<ServiceStackHost>> AfterPluginsLoaded { get; set; } = [];
/// <summary>
/// Register callbacks that's fired after the AppHost is initialized
/// </summary>
public List<Action<IAppHost>> AfterInitCallbacks { get; set; } = [];
/// <summary>
/// Register static callbacks fired after the AppHost is initialized
/// </summary>
public static List<Action<ServiceStackHost>> GlobalAfterAppHostInit { get; } = new();
/// <summary>
/// Register callbacks that's fired when AppHost is disposed
/// </summary>
public List<Action<IAppHost>> OnDisposeCallbacks { get; set; } = [];
/// <summary>
/// Register callbacks to execute at the end of a Request
/// </summary>
public List<Action<IRequest>> OnEndRequestCallbacks { get; set; } = [];
/// <summary>
/// Register highest priority IHttpHandler callbacks
/// </summary>
public List<Func<IHttpRequest, IHttpHandler>> RawHttpHandlers { get; set; }
internal Func<IHttpRequest, IHttpHandler>[] RawHttpHandlersArray;
/// <summary>
/// Get "Catch All" IHttpHandler predicate IHttpHandler's, e.g. Used by HTML View Engines
/// </summary>
public List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; } = [];
internal HttpHandlerResolverDelegate[] CatchAllHandlersArray;
/// <summary>
/// Register fallback Request Handlers e.g. Used by #Script & Razor Page Based Routing
/// </summary>
public List<HttpHandlerResolverDelegate> FallbackHandlers { get; set; } = [];
internal HttpHandlerResolverDelegate[] FallbackHandlersArray;
/// <summary>
/// Fallback IServiceStackHandler to handle Error Responses
/// </summary>
public IServiceStackHandler GlobalHtmlErrorHttpHandler { get; set; }
/// <summary>
/// Register Custom IServiceStackHandler to handle specific HttpStatusCode's
/// </summary>
public Dictionary<HttpStatusCode, IServiceStackHandler> CustomErrorHttpHandlers { get; set; } = new()
{
[HttpStatusCode.NotFound] = new NotFoundHttpHandler(),
[HttpStatusCode.Forbidden] = new ForbiddenHttpHandler(),
};
/// <summary>
/// Captured StartUp Exceptions
/// </summary>
public List<ResponseStatus> StartUpErrors { get; set; } = [];
/// <summary>
/// Captured Unobserved Async Errors
/// </summary>
public List<ResponseStatus> AsyncErrors { get; set; } = [];
/// <summary>
/// Which plugins were loaded in this AppHost
/// </summary>
public List<string> PluginsLoaded { get; set; } = [];
/// <summary>
/// Collection of added plugins.
/// </summary>
public List<IPlugin> Plugins { get; set; } = [];
/// <summary>
/// Writable Virtual File Source, uses FileSystemVirtualFiles at content root by default
/// </summary>
public IVirtualFiles VirtualFiles { get; set; }
/// <summary>
/// Virtual File Sources from WebRoot, typically a MultiVirtualFiles containing a cascading list of Sources
/// </summary>
public IVirtualPathProvider VirtualFileSources { get; set; }
/// <summary>
/// FileSystem VFS for WebRoot
/// </summary>
public IVirtualDirectory RootDirectory =>
(VirtualFileSources.GetFileSystemVirtualFiles()
?? VirtualFileSources
?? new FileSystemVirtualFiles(GetWebRootPath())).RootDirectory;
/// <summary>
/// The Content Root Directory for this AppHost
/// </summary>
public IVirtualDirectory ContentRootDirectory =>
VirtualFiles?.RootDirectory
?? new FileSystemVirtualFiles(MapProjectPath("~/")).RootDirectory;
/// <summary>
/// Insert higher priority VFS providers at the start of the VFS providers list
/// </summary>
public List<IVirtualPathProvider> InsertVirtualFileSources { get; set; } =
[
new MemoryVirtualFiles() //allow injecting files
];
/// <summary>
/// Append lower priority VFS providers at the end of the VFS providers list
/// </summary>
public List<IVirtualPathProvider> AddVirtualFileSources { get; set; } = [];
public List<Action<IRequest, object>> GatewayRequestFilters { get; set; } = [];
internal Action<IRequest, object>[] GatewayRequestFiltersArray;
public List<Func<IRequest, object, Task>> GatewayRequestFiltersAsync { get; set; } = [];
internal Func<IRequest, object, Task>[] GatewayRequestFiltersAsyncArray;
public List<Action<IRequest, object>> GatewayResponseFilters { get; set; } = [];
internal Action<IRequest, object>[] GatewayResponseFiltersArray;
public List<Func<IRequest, object, Task>> GatewayResponseFiltersAsync { get; set; } = [];
internal Func<IRequest, object, Task>[] GatewayResponseFiltersAsyncArray;
/// <summary>
/// The fallback ScriptContext to use if no SharpPagesFeature plugin was registered
/// </summary>
public ScriptContext DefaultScriptContext { get; set; }
/// <summary>
/// Global #Script ScriptContext for AppHost. Returns SharpPagesFeature plugin or fallsback to DefaultScriptContext.
/// </summary>
public ScriptContext ScriptContext => scriptContext ??= (GetPlugin<SharpPagesFeature>() ?? DefaultScriptContext);
private ScriptContext scriptContext;
/// <summary>
/// Evaluate Expressions in ServiceStack's ScriptContext.
/// Can be overridden if you want to customize how different expressions are evaluated.
/// </summary>
public virtual object EvalExpressionCached(string expr) => JS.evalCached(ScriptContext, expr);
public virtual object EvalExpression(string expr) => JS.eval(ScriptContext, expr);
/// <summary>
/// Evaluate a script value, `IScriptValue.Expression` results are cached globally.
/// If `IRequest` is provided, results from the same `IScriptValue.Eval` are cached per request.
/// </summary>
public virtual object EvalScriptValue(IScriptValue scriptValue, IRequest req = null, Dictionary<string, object> args=null)
{
if (ResolveScriptValue(scriptValue, out var exprValue))
return exprValue;
var evalCode = ScriptCodeUtils.EnsureReturn(scriptValue.Eval);
object value = null;
var evalCacheKey = JS.EvalCacheKeyPrefix + evalCode;
if (!scriptValue.NoCache && req?.Items.TryGetValue(evalCacheKey, out value) == true)
return value;
// Cache AST Globally
var cachedCodePage = JS.scriptCached(ScriptContext, evalCode);
var evalCodeValue = EvalScript(new PageResult(cachedCodePage), req, args);
if (!scriptValue.NoCache && req != null)
req.Items[evalCacheKey] = evalCodeValue;
return evalCodeValue;
}
/// <summary>
/// Evaluate a script value, `IScriptValue.Expression` results are cached globally.
/// If `IRequest` is provided, results from the same `IScriptValue.Eval` are cached per request.
/// </summary>
public virtual async Task<object> EvalScriptValueAsync(IScriptValue scriptValue, IRequest req = null, Dictionary<string, object> args=null)
{
if (ResolveScriptValue(scriptValue, out var exprValue))
return exprValue;
var evalCode = ScriptCodeUtils.EnsureReturn(scriptValue.Eval);
object value = null;
var evalCacheKey = JS.EvalCacheKeyPrefix + evalCode;
if (!scriptValue.NoCache && req?.Items.TryGetValue(evalCacheKey, out value) == true)
return value;
// Cache AST Globally
var cachedCodePage = JS.scriptCached(ScriptContext, evalCode);
var evalCodeValue = await EvalScriptAsync(new PageResult(cachedCodePage), req, args).ConfigAwait();
if (!scriptValue.NoCache && req != null)
req.Items[evalCacheKey] = evalCodeValue;
return evalCodeValue;
}
private bool ResolveScriptValue(IScriptValue scriptValue, out object exprValue)
{
if (scriptValue == null)
throw new ArgumentNullException(nameof(scriptValue));
if (scriptValue.Value != null)
{
exprValue = scriptValue.Value;
return true;
}
if (scriptValue.Expression != null)
{
{
exprValue = !scriptValue.NoCache
? EvalExpressionCached(scriptValue.Expression)
: JS.eval(scriptValue.Expression);
return true;
}
}
exprValue = null;
return scriptValue.Eval == null;
}
private static void InitPageResult(PageResult pageResult, IRequest req, Dictionary<string, object> args)
{
if (args != null)
{
foreach (var entry in args)
{
pageResult.Args[entry.Key] = entry.Value;
}
}
if (req != null)
{
pageResult.Args[ScriptConstants.Request] = req;
pageResult.Args[ScriptConstants.Dto] = req.Dto;
}
}
/// <summary>
/// Override to intercept sync #Script execution
/// </summary>
public virtual object EvalScript(PageResult pageResult, IRequest req = null, Dictionary<string, object> args=null)
{
InitPageResult(pageResult, req, args);
if (!pageResult.EvaluateResult(out var returnValue))
ScriptContextUtils.ThrowNoReturn();
return ScriptLanguage.UnwrapValue(returnValue);
}
/// <summary>
/// Override to intercept async #Script execution
/// </summary>
public virtual async Task<object> EvalScriptAsync(PageResult pageResult, IRequest req = null, Dictionary<string, object> args=null)
{
InitPageResult(pageResult, req, args);
var ret = await pageResult.EvaluateResultAsync().ConfigAwait();
if (!ret.Item1)
ScriptContextUtils.ThrowNoReturn();
return ScriptLanguage.UnwrapValue(ret.Item2);
}
/// <summary>
/// Executed immediately before a Service is executed. Use return to change the request DTO used, must be of the same type.
/// </summary>
public virtual object OnPreExecuteServiceFilter(IService service, object request, IRequest httpReq, IResponse httpRes)
{
return request;
}
/// <summary>
/// Executed immediately after a service is executed. Use return to change response used.
/// </summary>
public virtual object OnPostExecuteServiceFilter(IService service, object response, IRequest httpReq, IResponse httpRes)
{
return response;
}
/// <summary>
/// Occurs when the Service throws an Service Gateway Exception
/// </summary>
public virtual async Task OnGatewayException(IRequest httpReq, object request, Exception ex)
{
httpReq.Items[nameof(OnGatewayException)] = bool.TrueString;
foreach (var errorHandler in GatewayExceptionHandlers)
{
errorHandler(httpReq, request, ex);
}
foreach (var errorHandler in GatewayExceptionHandlersAsync)
{
await errorHandler(httpReq, request, ex).ConfigAwait();
}
}
/// <summary>
/// Occurs when the Service throws an Exception.
/// </summary>
public virtual async Task<object> OnServiceException(IRequest httpReq, object request, Exception ex)
{
httpReq.Items[nameof(OnServiceException)] = bool.TrueString;
object lastError = null;
foreach (var errorHandler in ServiceExceptionHandlers)
{
lastError = errorHandler(httpReq, request, ex) ?? lastError;
}
foreach (var errorHandler in ServiceExceptionHandlersAsync)
{
lastError = await errorHandler(httpReq, request, ex).ConfigAwait() ?? lastError;
}
return lastError;
}
/// <summary>
/// Occurs when an exception is thrown whilst processing a request.
/// </summary>
public virtual async Task OnUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex)
{
foreach (var errorHandler in UncaughtExceptionHandlers)
{
errorHandler(httpReq, httpRes, operationName, ex);
}
foreach (var errorHandler in UncaughtExceptionHandlersAsync)
{
await errorHandler(httpReq, httpRes, operationName, ex).ConfigAwait();
}
}
[Obsolete("Use HandleResponseException")]