Inheritance: IHttpHandlerFactory
Example #1
0
        public static string GetBaseUrl(this IRequest httpReq)
        {
            var baseUrl = HttpHandlerFactory.GetBaseUrl();

            if (baseUrl != null)
            {
                return(baseUrl);
            }

            var handlerPath = HostContext.Config.HandlerFactoryPath;

            if (handlerPath != null)
            {
                var absoluteUri = httpReq.AbsoluteUri;
                var pos         = absoluteUri.IndexOf(handlerPath, StringComparison.OrdinalIgnoreCase);
                if (pos >= 0)
                {
                    baseUrl = absoluteUri.Substring(0, pos + handlerPath.Length);
                    return(baseUrl);
                }
                return("/" + handlerPath);
            }

            return(new Uri(httpReq.AbsoluteUri).GetLeftPart(UriPartial.Authority)
                   .CombineWith(handlerPath)
                   .TrimEnd('/'));
        }
Example #2
0
        public override string GetBaseUrl(IRequest httpReq)
        {
            var useHttps = UseHttps(httpReq);
            var baseUrl  = HttpHandlerFactory.GetBaseUrl();

            if (baseUrl != null)
            {
                return(baseUrl.NormalizeScheme(useHttps));
            }

            baseUrl = httpReq.AbsoluteUri.InferBaseUrl(fromPathInfo: httpReq.PathInfo);
            if (baseUrl != null)
            {
                return(baseUrl.NormalizeScheme(useHttps));
            }

            var handlerPath = Config.HandlerFactoryPath;

            var aspReq = (HttpRequestBase)httpReq.OriginalRequest;

            baseUrl = aspReq.Url.Scheme + "://" + aspReq.Url.Authority +
                      aspReq.ApplicationPath?.TrimEnd('/') + "/";

            return(baseUrl
                   .NormalizeScheme(useHttps)
                   .CombineWith(handlerPath)
                   .TrimEnd('/'));
        }
        public virtual Task ProcessRequest(HttpContext context, Func <Task> next)
        {
            var operationName = context.Request.GetOperationName().UrlDecode() ?? "Home";

            var httpReq = context.ToRequest(operationName);
            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                if (serviceStackHandler is NotFoundHttpHandler)
                {
                    return(next());
                }

                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return(task);
            }

            return(next());
        }
        protected override async Task ProcessRequestAsync(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return;
            }

            RequestContext.Instance.StartRequestContext();

            var operationName = context.Request.GetOperationName().UrlDecode();

            var httpReq = context.ToRequest(operationName);
            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                await HostContext.Async.ContinueWith(httpReq, task, x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);

                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return;
            }

            throw new NotImplementedException($"Cannot execute handler: {handler} at PathInfo: {httpReq.PathInfo}");
        }
Example #5
0
        protected override Task ProcessRequestAsync(HttpListenerContext context)
        {
            if (string.IsNullOrEmpty(context.Request.RawUrl))
            {
                return(((object)null).AsTaskResult());
            }

            var operationName = context.Request.GetOperationName();

            var httpReq = context.ToRequest(operationName);
            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return(task);
            }

            return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
                   .AsTaskException());
        }
        public virtual async Task ProcessRequest(HttpContext context, Func <Task> next)
        {
            //Keep in sync with Kestrel/AppSelfHostBase.cs
            var operationName = context.Request.GetOperationName().UrlDecode() ?? "Home";
            var pathInfo      = context.Request.Path.HasValue
                ? context.Request.Path.Value
                : "/";

            var mode = Config.HandlerFactoryPath;

            if (!string.IsNullOrEmpty(mode))
            {
                if (pathInfo.IndexOf(mode, StringComparison.Ordinal) != 1)
                {
                    await next();
                }

                pathInfo = pathInfo.Substring(mode.Length + 1);
            }

            RequestContext.Instance.StartRequestContext();

            var httpReq = new NetCoreRequest(context, operationName, RequestAttributes.None, pathInfo);

            httpReq.RequestAttributes = httpReq.GetAttributes();

            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                if (serviceStackHandler is NotFoundHttpHandler)
                {
                    await next();
                }

                if (!string.IsNullOrEmpty(serviceStackHandler.RequestName))
                {
                    operationName = serviceStackHandler.RequestName;
                }

                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                await HostContext.Async.ContinueWith(httpReq, task, x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);

                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return;
            }

            await next();
        }
        /// <summary>
        /// Initializes the AppHost.
        /// Calls the <see cref="Configure"/> method.
        /// Should be called before start.
        /// </summary>
        public virtual ServiceStackHost Init()
        {
            if (Instance != null)
            {
                throw new InvalidDataException($"ServiceStackHost.Instance has already been set ({Instance.GetType().Name})");
            }

            Service.GlobalResolver = Instance = this;

            Config = HostConfig.ResetInstance();
            OnConfigLoad();

            AbstractVirtualFileBase.ScanSkipPaths = Config.ScanSkipPaths;
            ResourceVirtualDirectory.EmbeddedResourceTreatAsFiles = Config.EmbeddedResourceTreatAsFiles;

            Config.DebugMode = GetType().GetAssembly().IsDebugBuild();
            if (Config.DebugMode)
            {
                Plugins.Add(new RequestInfoFeature());
            }

            OnBeforeInit();
            ServiceController.Init();
            Configure(Container);

            if (Config.StrictMode == null && Config.DebugMode)
            {
                Config.StrictMode = true;
            }

            ConfigurePlugins();

            List <IVirtualPathProvider> pathProviders = null;

            if (VirtualFileSources == null)
            {
                pathProviders = GetVirtualFileSources().Where(x => x != null).ToList();

                VirtualFileSources = pathProviders.Count > 1
                    ? new MultiVirtualFiles(pathProviders.ToArray())
                    : pathProviders.First();
            }

            if (VirtualFiles == null)
            {
                VirtualFiles = pathProviders?.FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles
                               ?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles;
            }

            OnAfterInit();

            LogInitComplete();

            HttpHandlerFactory.Init();

            return(this);
        }
Example #8
0
        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('/'));
        }
Example #9
0
        public virtual string GetBaseUrl(IRequest httpReq)
        {
            var useHttps = UseHttps(httpReq);
            var baseUrl  = HttpHandlerFactory.GetBaseUrl();

            if (baseUrl != null)
            {
                return(baseUrl.NormalizeScheme(useHttps));
            }

            baseUrl = httpReq.AbsoluteUri.InferBaseUrl(fromPathInfo: httpReq.PathInfo);
            if (baseUrl != null)
            {
                return(baseUrl.NormalizeScheme(useHttps));
            }

            var handlerPath = Config.HandlerFactoryPath;

            return(new Uri(httpReq.AbsoluteUri).GetLeftAuthority()
                   .NormalizeScheme(useHttps)
                   .CombineWith(handlerPath)
                   .TrimEnd('/'));
        }
Example #10
0
        public static string GetBaseUrl(this IRequest httpReq)
        {
            var baseUrl = HttpHandlerFactory.GetBaseUrl();

            if (baseUrl != null)
            {
                return(baseUrl);
            }

            var handlerPath = HostContext.Config.ServiceStackHandlerFactoryPath;

            if (handlerPath != null)
            {
                var pos = httpReq.AbsoluteUri.IndexOf(handlerPath, StringComparison.InvariantCultureIgnoreCase);
                if (pos >= 0)
                {
                    baseUrl = httpReq.AbsoluteUri.Substring(0, pos + handlerPath.Length);
                    return(baseUrl);
                }
                return("/" + handlerPath);
            }

            return("/"); //Can't infer Absolute Uri, fallback to root relative path
        }
        public virtual Task ProcessRequest(HttpContext context, Func <Task> next)
        {
            //Keep in sync with Kestrel/AppSelfHostBase.cs
            var operationName = context.Request.GetOperationName().UrlDecode() ?? "Home";
            var pathInfo      = context.Request.Path.HasValue
                ? context.Request.Path.Value
                : "/";

            var mode = Config.HandlerFactoryPath;

            if (!string.IsNullOrEmpty(mode))
            {
                if (pathInfo.IndexOf(mode, StringComparison.Ordinal) != 1)
                {
                    return(next());
                }

                pathInfo = pathInfo.Substring(mode.Length + 1);
            }

#if NETSTANDARD1_6
            // This fixes problems if the RequestContext.Instance.Items was touched on startup or outside of request context.
            // It would turn it into a static dictionary instead flooding request with each-others values.
            // This can already happen if I register a Funq.Container Request Scope type and Resolve it on startup.
            RequestContext.Instance.StartRequestContext();
#endif

            var httpReq = new NetCoreRequest(context, operationName, RequestAttributes.None, pathInfo);
            httpReq.RequestAttributes = httpReq.GetAttributes();

            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;
            if (serviceStackHandler != null)
            {
                if (serviceStackHandler is NotFoundHttpHandler)
                {
                    return(next());
                }

                if (!string.IsNullOrEmpty(serviceStackHandler.RequestName))
                {
                    operationName = serviceStackHandler.RequestName;
                }

                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                HostContext.Async.ContinueWith(httpReq, task, x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return(task);
            }

            return(next());
        }
        private IHttpHandler GetHandlerForPathParts(string[] pathParts)
        {
            var pathController = string.Intern(pathParts[0].ToLower());

            if (pathParts.Length == 1)
            {
                if (pathController == "metadata")
                {
                    return(new IndexMetadataHandler());
                }

                return(null);
            }

            var pathAction = string.Intern(pathParts[1].ToLower());

            if (pathAction == "wsdl")
            {
                if (pathController == "soap11")
                {
                    return(new Soap11WsdlMetadataHandler());
                }
                if (pathController == "soap12")
                {
                    return(new Soap12WsdlMetadataHandler());
                }
            }

            if (pathAction != "metadata")
            {
                return(null);
            }

            switch (pathController)
            {
            case "json":
                return(new JsonMetadataHandler());

            case "xml":
                return(new XmlMetadataHandler());

            case "jsv":
                return(new JsvMetadataHandler());

            case "soap11":
                return(new Soap11MetadataHandler());

            case "soap12":
                return(new Soap12MetadataHandler());

            case "types":

                if (HostContext.Config == null ||
                    HostContext.Config.MetadataTypesConfig == null)
                {
                    return(null);
                }

                if (HostContext.Config.MetadataTypesConfig.BaseUrl == null)
                {
                    HostContext.Config.MetadataTypesConfig.BaseUrl = HttpHandlerFactory.GetBaseUrl();
                }

                return(new MetadataTypesHandler {
                    Config = HostContext.Config.MetadataTypesConfig
                });

            case "operations":

                return(new CustomResponseHandler((httpReq, httpRes) =>
                                                 HostContext.AppHost.HasAccessToMetadata(httpReq, httpRes)
                            ? HostContext.Metadata.GetOperationDtos()
                            : null, "Operations"));

            default:
                string contentType;
                if (HostContext.ContentTypes
                    .ContentTypeFormats.TryGetValue(pathController, out contentType))
                {
                    var format = ContentFormat.GetContentFormat(contentType);
                    return(new CustomMetadataHandler(contentType, format));
                }
                break;
            }
            return(null);
        }
        /// <summary>
        /// Initializes the AppHost.
        /// Calls the <see cref="Configure"/> method.
        /// Should be called before start.
        /// </summary>
        public virtual ServiceStackHost Init()
        {
            if (Instance != null)
            {
                throw new InvalidDataException($"ServiceStackHost.Instance has already been set ({Instance.GetType().Name})");
            }

            Service.GlobalResolver = Instance = this;

            RegisterLicenseKey(AppSettings.GetNullableString("servicestack:license"));

            if (ServiceController == null)
            {
                ServiceController = CreateServiceController(ServiceAssemblies.ToArray());
            }

            Config = HostConfig.ResetInstance();
            OnConfigLoad();

            AbstractVirtualFileBase.ScanSkipPaths = Config.ScanSkipPaths;
            ResourceVirtualDirectory.EmbeddedResourceTreatAsFiles = Config.EmbeddedResourceTreatAsFiles;

            OnBeforeInit();
            ServiceController.Init();

            BeforeConfigure.Each(fn => fn(this));
            Configure(Container);
            AfterConfigure.Each(fn => fn(this));

            if (Config.StrictMode == null && Config.DebugMode)
            {
                Config.StrictMode = true;
            }

            if (!Config.DebugMode)
            {
                Plugins.RemoveAll(x => x is RequestInfoFeature);
            }

            ConfigurePlugins();

            List <IVirtualPathProvider> pathProviders = null;

            if (VirtualFileSources == null)
            {
                pathProviders = GetVirtualFileSources().Where(x => x != null).ToList();

                VirtualFileSources = pathProviders.Count > 1
                    ? new MultiVirtualFiles(pathProviders.ToArray())
                    : pathProviders.First();
            }

            if (VirtualFiles == null)
            {
                VirtualFiles = pathProviders?.FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles
                               ?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles;
            }

            OnAfterInit();

            PopulateArrayFilters();

            LogInitComplete();

            HttpHandlerFactory.Init();

            return(this);
        }
        //After configure called
        public virtual void InitFinal()
        {
            if (Config.EnableFeatures != Feature.All)
            {
                if ((Feature.Xml & Config.EnableFeatures) != Feature.Xml)
                {
                    Config.IgnoreFormatsInMetadata.Add("xml");
                    Config.PreferredContentTypes.Remove(MimeTypes.Xml);
                }
                if ((Feature.Json & Config.EnableFeatures) != Feature.Json)
                {
                    Config.IgnoreFormatsInMetadata.Add("json");
                    Config.PreferredContentTypes.Remove(MimeTypes.Json);
                }
                if ((Feature.Jsv & Config.EnableFeatures) != Feature.Jsv)
                {
                    Config.IgnoreFormatsInMetadata.Add("jsv");
                    Config.PreferredContentTypes.Remove(MimeTypes.Jsv);
                }
                if ((Feature.Csv & Config.EnableFeatures) != Feature.Csv)
                {
                    Config.IgnoreFormatsInMetadata.Add("csv");
                    Config.PreferredContentTypes.Remove(MimeTypes.Csv);
                }
                if ((Feature.Html & Config.EnableFeatures) != Feature.Html)
                {
                    Config.IgnoreFormatsInMetadata.Add("html");
                    Config.PreferredContentTypes.Remove(MimeTypes.Html);
                }
                if ((Feature.Soap11 & Config.EnableFeatures) != Feature.Soap11)
                {
                    Config.IgnoreFormatsInMetadata.Add("soap11");
                }
                if ((Feature.Soap12 & Config.EnableFeatures) != Feature.Soap12)
                {
                    Config.IgnoreFormatsInMetadata.Add("soap12");
                }
            }

            if ((Feature.Html & Config.EnableFeatures) != Feature.Html)
            {
                Plugins.RemoveAll(x => x is HtmlFormat);
            }

            if ((Feature.Csv & Config.EnableFeatures) != Feature.Csv)
            {
                Plugins.RemoveAll(x => x is CsvFormat);
            }

            if ((Feature.PredefinedRoutes & Config.EnableFeatures) != Feature.PredefinedRoutes)
            {
                Plugins.RemoveAll(x => x is PredefinedRoutesFeature);
            }

            if ((Feature.Metadata & Config.EnableFeatures) != Feature.Metadata)
            {
                Plugins.RemoveAll(x => x is MetadataFeature);
                Plugins.RemoveAll(x => x is NativeTypesFeature);
            }

            if ((Feature.RequestInfo & Config.EnableFeatures) != Feature.RequestInfo)
            {
                Plugins.RemoveAll(x => x is RequestInfoFeature);
            }

            if ((Feature.Razor & Config.EnableFeatures) != Feature.Razor)
            {
                Plugins.RemoveAll(x => x is IRazorPlugin);    //external
            }
            if ((Feature.ProtoBuf & Config.EnableFeatures) != Feature.ProtoBuf)
            {
                Plugins.RemoveAll(x => x is IProtoBufPlugin); //external
            }
            if ((Feature.MsgPack & Config.EnableFeatures) != Feature.MsgPack)
            {
                Plugins.RemoveAll(x => x is IMsgPackPlugin);  //external
            }
            var plugins = Plugins.ToArray();

            delayLoadPlugin = true;
            LoadPluginsInternal(plugins);

            AfterPluginsLoaded();

            Metadata.Config.IgnoreFormats = Config.IgnoreFormatsInMetadata;

            if (!TestMode && Container.Exists <IAuthSession>())
            {
                throw new Exception(ErrorMessages.ShouldNotRegisterAuthSession);
            }

            if (!Container.Exists <ICacheClient>())
            {
                if (Container.Exists <IRedisClientsManager>())
                {
                    Container.Register(c => c.Resolve <IRedisClientsManager>().GetCacheClient());
                }
                else
                {
                    Container.Register <ICacheClient>(new MemoryCacheClient());
                }
            }

            if (!Container.Exists <MemoryCacheClient>())
            {
                Container.Register(new MemoryCacheClient());
            }

            if (Container.Exists <IMessageService>() &&
                !Container.Exists <IMessageFactory>())
            {
                Container.Register(c => c.Resolve <IMessageService>().MessageFactory);
            }

            if (Container.Exists <IUserAuthRepository>() &&
                !Container.Exists <IAuthRepository>())
            {
                Container.Register <IAuthRepository>(c => c.Resolve <IUserAuthRepository>());
            }

            if (Config.UseJsObject)
            {
                JS.Configure();
            }

            if (Config.LogUnobservedTaskExceptions)
            {
                TaskScheduler.UnobservedTaskException += (sender, args) =>
                {
                    args.SetObserved();
                    args.Exception.Handle(ex =>
                    {
                        lock (AsyncErrors)
                        {
                            AsyncErrors.Add(DtoUtils.CreateErrorResponse(null, ex).GetResponseStatus());
                            return(true);
                        }
                    });
                };
            }

            foreach (var callback in AfterInitCallbacks)
            {
                callback(this);
            }
            ////Register any routes configured on Routes
            //foreach (var restPath in Routes)
            //{
            //    ServiceController.RegisterRestPath(restPath);

            //    //Auto add Route Attributes so they're available in T.ToUrl() extension methods
            //    restPath.RequestType
            //        .AddAttributes(new RouteAttribute(restPath.Path, restPath.AllowedVerbs)
            //        {
            //            Priority = restPath.Priority,
            //            Summary = restPath.Summary,
            //            Notes = restPath.Notes,
            //        });
            //}

            HttpHandlerFactory.Init();
        }
Example #15
0
        public virtual async Task ProcessRequest(HttpContext context, Func <Task> next)
        {
            if (NetCoreHandler != null)
            {
                var handled = await NetCoreHandler(context);

                if (handled)
                {
                    return;
                }
            }

            //Keep in sync with Kestrel/AppSelfHostBase.cs
            var operationName = context.Request.GetOperationName().UrlDecode() ?? "Home";
            var pathInfo      = context.Request.Path.HasValue
                ? context.Request.Path.Value
                : "/";

            var mode = Config.HandlerFactoryPath;

            if (!string.IsNullOrEmpty(mode))
            {
                var includedInPathInfo = pathInfo.IndexOf(mode, StringComparison.Ordinal) == 1;
                var includedInPathBase = context.Request.PathBase.HasValue &&
                                         context.Request.PathBase.Value.IndexOf(mode, StringComparison.Ordinal) == 1;
                if (!includedInPathInfo && !includedInPathBase)
                {
                    await next();

                    return;
                }

                if (includedInPathInfo)
                {
                    pathInfo = pathInfo.Substring(mode.Length + 1);
                }
            }

            RequestContext.Instance.StartRequestContext();

            NetCoreRequest httpReq;
            IResponse      httpRes;

            System.Web.IHttpHandler handler;

            try
            {
                httpReq = new NetCoreRequest(context, operationName, RequestAttributes.None, pathInfo);
                httpReq.RequestAttributes = httpReq.GetAttributes() | RequestAttributes.Http;

                httpRes = httpReq.Response;
                handler = HttpHandlerFactory.GetHandler(httpReq);

                if (BeforeNextMiddleware != null)
                {
                    var holdNext = next;
                    next = async() => {
                        await BeforeNextMiddleware(httpReq);
                        await holdNext();
                    };
                }
            }
            catch (Exception ex) //Request Initialization error
            {
                var logFactory = context.Features.Get <ILoggerFactory>();
                if (logFactory != null)
                {
                    var log = logFactory.CreateLogger(GetType());
                    log.LogError(default(EventId), ex, ex.Message);
                }

                context.Response.ContentType = MimeTypes.PlainText;
                await context.Response.WriteAsync($"{ex.GetType().Name}: {ex.Message}");

                if (Config.DebugMode)
                {
                    await context.Response.WriteAsync($"\nStackTrace:\n{ex.StackTrace}");
                }
                return;
            }

            if (handler is IServiceStackHandler serviceStackHandler)
            {
                if (serviceStackHandler is NotFoundHttpHandler)
                {
                    await next();

                    return;
                }

                if (!string.IsNullOrEmpty(serviceStackHandler.RequestName))
                {
                    operationName = serviceStackHandler.RequestName;
                }

                if (serviceStackHandler is RestHandler restHandler)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                try
                {
                    await serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                }
                catch (Exception ex)
                {
                    var logFactory = context.Features.Get <ILoggerFactory>();
                    if (logFactory != null)
                    {
                        var log = logFactory.CreateLogger(GetType());
                        log.LogError(default(EventId), ex, ex.Message);
                    }
                }
                finally
                {
                    httpRes.Close();
                }
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return;
            }

            await next();
        }
        public virtual async Task ProcessRequest(HttpContext context, Func <Task> next)
        {
            //Keep in sync with Kestrel/AppSelfHostBase.cs
            var operationName = context.Request.GetOperationName().UrlDecode() ?? "Home";
            var pathInfo      = context.Request.Path.HasValue
                ? context.Request.Path.Value
                : "/";

            var mode = Config.HandlerFactoryPath;

            if (!string.IsNullOrEmpty(mode))
            {
                if (pathInfo.IndexOf(mode, StringComparison.Ordinal) != 1)
                {
                    await next();
                }

                pathInfo = pathInfo.Substring(mode.Length + 1);
            }

            RequestContext.Instance.StartRequestContext();

            var httpReq = new NetCoreRequest(context, operationName, RequestAttributes.None, pathInfo);

            httpReq.RequestAttributes = httpReq.GetAttributes();

            var httpRes = httpReq.Response;
            var handler = HttpHandlerFactory.GetHandler(httpReq);

            var serviceStackHandler = handler as IServiceStackHandler;

            if (serviceStackHandler != null)
            {
                if (serviceStackHandler is NotFoundHttpHandler)
                {
                    await next();

                    return;
                }

                if (!string.IsNullOrEmpty(serviceStackHandler.RequestName))
                {
                    operationName = serviceStackHandler.RequestName;
                }

                var restHandler = serviceStackHandler as RestHandler;
                if (restHandler != null)
                {
                    httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
                }

                try
                {
                    await serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
                }
                catch (Exception ex)
                {
                    var logFactory = context.Features.Get <ILoggerFactory>();
                    var log        = logFactory.CreateLogger(GetType());
                    log.LogError(default(EventId), ex, ex.Message);
                }
                finally
                {
                    httpRes.Close();
                }
                //Matches Exceptions handled in HttpListenerBase.InitTask()

                return;
            }

            await next();
        }
Example #17
0
        /// <summary>
        /// Initializes the AppHost.
        /// Calls the <see cref="Configure"/> method.
        /// Should be called before start.
        /// </summary>
        public virtual ServiceStackHost Init()
        {
            if (Instance != null)
            {
                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.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);
            //    }
            //}
            //var priorityPlugins = Plugins.WithPriority().PriorityOrdered().Map(x => (IPlugin)x);
            //priorityPlugins.ForEach(RunPreConfigure);
            //configInstances.ForEach(RunPreConfigure);

            if (ServiceController == null)
            {
                ServiceController = CreateServiceController(ServiceAssemblies.ToArray());
            }

            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);
            //    }
            //}
            //preStartupConfigs.ForEach(RunConfigure);
            //BeforeConfigure.Each(fn => fn(this));

            Configure(Container);

            //AfterConfigure.Each(fn => fn(this));

            //postStartupConfigs.ForEach(RunConfigure);

            if (Config.StrictMode == null && Config.DebugMode)
            {
                Config.StrictMode = true;
            }

            //if (!Config.DebugMode)
            //    Plugins.RemoveAll(x => x is RequestInfoFeature);

            //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();
            }

            //if (VirtualFiles == null)
            //    VirtualFiles = pathProviders?.FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles
            //        ?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles;

            OnAfterInit();

            //configInstances.ForEach(RunPostInitPlugin);

            PopulateArrayFilters();

            LogInitComplete();

            HttpHandlerFactory.Init();

            foreach (var callback in AfterInitCallbacks)
            {
                callback(this);
            }

            Plugins.ForEach(RunAfterInitAppHost);
            //configInstances.ForEach(RunAfterInitAppHost);

            ReadyAt = DateTime.UtcNow;

            return(this);
        }