Exemplo n.º 1
0
        public void LoadSectionModelFromCsv()
        {
            IEnumerable <string> collection;
            string path = StaticFileHandler.GetOpenDialogFilePath("section model", "csv");

            if (path == "")
            {
                return;
            }
            try
            {
                collection = StaticFileHandler.ReadAllFromTextFile(path);
            }
            catch (Exception e)
            {
                Annalist.Instance.DisplayStatus("Section Builder", "E252", e.Message);
                return;
            }
            UpdateFromStringArray(collection.ToArray());
            if (EvaluateNeedToPerformInternalIntegrityCheck())
            {
                CheckInternalIntegrity();
            }
            Annalist.Instance.DisplayStatus("Section Builder", "I252");
        }
        private string getNamespaceFromFilePath(string projectNamespace, string filePathRelativeToProject)
        {
            var tokens = filePathRelativeToProject.Separate(System.IO.Path.DirectorySeparatorChar.ToString(), false);

            tokens = tokens.Take(tokens.Count - 1).ToList();
            return(StaticFileHandler.CombineNamespacesAndProcessEwfIfNecessary(
                       projectNamespace,
                       StringTools.ConcatenateWithDelimiter(".", tokens.Select(i => EwlStatics.GetCSharpIdentifier(i.CapitalizeString())).ToArray())));
        }
Exemplo n.º 3
0
        public void Test_Fecthing_File_Content_When_File_Does_Not_Exist()
        {
            //arrange
            StaticFileHandler file = new StaticFileHandler();
            //act
            string fileContent = file.TryGetFile("C://WebPages//google//index.htm");

            //assert
            Assert.Equal("<HTML><BODY><h1>404 Not Found</h1><p>Web Page not found!!!!!!!!!!!</p></BODY></HTML>", fileContent);
        }
Exemplo n.º 4
0
        public void Test_Get_File_Content()
        {
            //arrange
            StaticFileHandler file = new StaticFileHandler();
            //act
            string fileContent = file.TryGetFile("C://WebPages//google//hello.htm");

            //assert
            Assert.Equal("<HTML><BODY><h1>Hello</h1></BODY></HTML>", fileContent);
        }
Exemplo n.º 5
0
        public void Test_Virtual_Path_To_Local_Path()
        {
            //arrange
            StaticFileHandler file = new StaticFileHandler();
            //act
            string filePath = file.ResolveVirtualPath("google.com/hello.htm", "C://WebPages//google", "google.com");

            //assert
            Assert.Equal("C://WebPages//google/hello.htm", filePath);
        }
Exemplo n.º 6
0
 public RequestHandler(
     StreamSocket socket,
     Request request,
     StaticFileHandler staticFileHandler,
     RequestParser requestParser)
 {
     _streamSocket      = socket;
     _request           = request;
     _staticFileHandler = staticFileHandler;
     _requestParser     = requestParser;
     _restHandler       = new RestHandler(socket, request);
 }
Exemplo n.º 7
0
        public Handler CreateAndAttachHandlers()
        {
            var headHandler       = new HeadHandler();
            var optionsHandler    = new OptionsHandler();
            var fileHandler       = new StaticFileHandler();
            var controllerHandler = new ControllerHandler();

            headHandler.SetSuccessor(optionsHandler);
            optionsHandler.SetSuccessor(fileHandler);
            fileHandler.SetSuccessor(controllerHandler);

            return(headHandler);
        }
Exemplo n.º 8
0
        public Handler CreateAndAttachHandlers()
        {
            var headHandler = new HeadHandler();
            var optionsHandler = new OptionsHandler();
            var fileHandler = new StaticFileHandler();
            var controllerHandler = new ControllerHandler();

            headHandler.SetSuccessor(optionsHandler);
            optionsHandler.SetSuccessor(fileHandler);
            fileHandler.SetSuccessor(controllerHandler);

            return headHandler;
        }
Exemplo n.º 9
0
 public Endpoint With(DirectoryInfo dirInfo, Func <HttpResponse, HttpResponse> gzipFuncImpl)
 {
     if (dirInfo.Exists)
     {
         //TODO: check format of `Route.PathTemplate` eg. '/{capture}/folder/*' would NOT work
         var            pathFilenameStartIndex = Route.PathTemplate.Length - 1; // (assumed) trailing '/*' to indicate start of filename
         RequestHandler fileHandler            = new StaticFileHandler(pathFilenameStartIndex, dirInfo, gzipFuncImpl).Handle;
         return(new Endpoint(Method, Route, Handler.From(fileHandler)));
     }
     else
     {
         throw new DirectoryNotFoundException($"The specified directory {dirInfo.FullName} could not be found.");
     }
 }
Exemplo n.º 10
0
 public HttpViewModel(string title) : base(title)
 {
     _clientList        = new ObservableCollection <IClientContext>();
     _uiDispatcher      = Dispatcher.CurrentDispatcher;
     _httpServer        = new HttpServer();
     _websocketHandler  = new WebsocketHandler("/ws");
     _staticFileHandler = new StaticFileHandler();
     _staticFileHandler.DefaultFiles.Add("index.html");
     _httpServer.Handlers.Add(_websocketHandler);
     _httpServer.Handlers.Add(_staticFileHandler);
     _httpServer.UnhandledRequestReceived += _httpServer_UnhandledRequestReceived;;
     _httpServer.WebSocketDataReceived    += _httpServer_WSDataReceived;
     _httpServer.WebSocketStatusChanged   += _httpServer_WebSocketStatusChanged;
 }
Exemplo n.º 11
0
        public DotNetWatcher(IReporter reporter, IFileSetFactory fileSetFactory, DotNetWatchOptions dotNetWatchOptions)
        {
            Ensure.NotNull(reporter, nameof(reporter));

            _reporter           = reporter;
            _processRunner      = new ProcessRunner(reporter);
            _dotnetWatchOptions = dotNetWatchOptions;
            _staticFileHandler  = new StaticFileHandler(reporter);

            _filters = new IWatchFilter[]
            {
                new MSBuildEvaluationFilter(fileSetFactory),
                new NoRestoreFilter(),
                new LaunchBrowserFilter(dotNetWatchOptions),
            };
        }
Exemplo n.º 12
0
        public void SaveSectionModelAsCsv() // method is intended to be dumb: is saves what user creates so no bother with integrity checks
        {
            List <string> collection = new List <string>();
            string        csvString;

            string path = StaticFileHandler.GetSaveDialogFilePath("section model", "csv");

            if (path == "")
            {
                return;
            }

            foreach (UserSpan span in Spans)
            {
                csvString = span.OrdinalDescription + ";"
                            + span.SelectedItem.CodeName + ";"
                            + span.TowerAbscissa.ToString() + ";"
                            + span.TowerOrdinate.ToString() + ";"
                            + span.TowerAPHeight.ToString() + ";"
                            + span.SpanLength.ToString() + ";"
                            + span.InsulatorSetLength.ToString() + ";"
                            + span.InsulatorSetWeight.ToString() + ";"
                            + span.InsulatorSetOpeningAngle.ToString() + ";"
                            + span.InsulatorSetIceLoad.ToString() + ";"
                            + span.SpanIceLoad.ToString() + ";"
                            + span.SpanWindLoad.ToString();

                collection.Add(csvString);
            }

            try
            {
                StaticFileHandler.WriteCollectionToTextFile(path, collection);
            }
            catch (Exception e)
            {
                Annalist.Instance.DisplayStatus("Section Builder", "E251", e.Message);
                return;
            }
            Annalist.Instance.DisplayStatus("Section Builder", "I251");
        }
Exemplo n.º 13
0
        public override void Configure(Container container)
        {
            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            //Set JSON web services to return idiomatic JSON camelCase properties
            JsConfig.EmitCamelCaseNames = true;
            JsConfig.IncludeNullValues  = true;

            //Register dependencies
            QWSessionFactory sf = new QWSessionFactory(ConfigurationManager.ConnectionStrings["qwdb"].ConnectionString);

            container.Register(c => sf.Factory.OpenSession()).ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<RepositoryProductMongo, IRepositoryProduct>();
            //container.RegisterAutoWiredAs<RepositoryVendorMongo, IRepositoryVendor>();

            //Enable CORS
            Plugins.Add(new CorsFeature()); //Plugins.Add(new CorsFeature(allowCredentials: true, allowOriginWhitelist: new[] { "http://localhost:8080" }));

            //Enable session
            Plugins.Add(new SessionFeature());

            SetConfig(new EndpointHostConfig
            {
                //DebugMode = true //Show StackTraces for easier debugging (default auto inferred by Debug/Release builds)
            });

            var basePath = HttpRuntime.AppDomainAppPath + "wwwroot\\";

            // Server static files
            CatchAllHandlers.Add(
                (httpMethod, pathInfo, filePath) =>
                StaticFileHandler.Factory(
                    basePath,
                    "/",
                    pathInfo
                    )
                );
        }
Exemplo n.º 14
0
        static HttpHandlerFactory()
        {
            //MONO doesn't implement this property
            var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline");

            if (pi != null)
            {
                IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]);
            }

            var appHost = HostContext.AppHost;
            var config  = appHost.Config;

            var isAspNetHost = HostContext.IsAspNetHost;

            WebHostPhysicalPath   = appHost.VirtualPathProvider.RootDirectory.RealPath;
            HostAutoRedirectsDirs = isAspNetHost && !Env.IsMono;

            //Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources
            var hostedAtRootPath = config.HandlerFactoryPath == null;

            //DefaultHttpHandler not supported in IntegratedPipeline mode
            if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono)
            {
                DefaultHttpHandler = new DefaultHttpHandler();
            }

            var rootFiles = appHost.VirtualPathProvider.GetRootFiles().ToList();

            foreach (var file in rootFiles)
            {
                var fileNameLower = file.Name.ToLower();
                if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower))
                {
                    //Can't serve Default.aspx pages so ignore and allow for next default document
                    if (!fileNameLower.EndsWith(".aspx"))
                    {
                        DefaultRootFileName = fileNameLower;
                        StaticFileHandler.SetDefaultFile(file.VirtualPath, file.ReadAllBytes(), file.LastModified);

                        if (DefaultHttpHandler == null)
                        {
                            DefaultHttpHandler = new StaticFileHandler {
                                VirtualNode = file
                            }
                        }
                        ;
                    }
                }
                WebHostRootFileNames.Add(fileNameLower);
            }

            foreach (var dir in appHost.VirtualPathProvider.GetRootDirectories())
            {
                WebHostRootFileNames.Add(dir.Name.ToLower());
            }

            if (!string.IsNullOrEmpty(config.DefaultRedirectPath))
            {
                DefaultHttpHandler = new RedirectHttpHandler {
                    RelativeUrl = config.DefaultRedirectPath
                }
            }
            ;

            if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath))
            {
                DefaultHttpHandler = new RedirectHttpHandler {
                    RelativeUrl = config.MetadataRedirectPath
                }
            }
            ;

            if (!string.IsNullOrEmpty(config.MetadataRedirectPath))
            {
                NonRootModeDefaultHttpHandler = new RedirectHttpHandler {
                    RelativeUrl = config.MetadataRedirectPath
                }
            }
            ;

            if (DefaultHttpHandler == null)
            {
                DefaultHttpHandler = NotFoundHttpHandler;
            }

            var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler;
            var debugDefaultHandler    = defaultRedirectHanlder != null
                ? defaultRedirectHanlder.RelativeUrl
                : typeof(DefaultHttpHandler).GetOperationName();

            SetApplicationBaseUrl(config.WebHostUrl);

            ForbiddenHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden);
            if (ForbiddenHttpHandler == null)
            {
                ForbiddenHttpHandler = new ForbiddenHttpHandler
                {
                    IsIntegratedPipeline = IsIntegratedPipeline,
                    WebHostPhysicalPath  = WebHostPhysicalPath,
                    WebHostRootFileNames = WebHostRootFileNames,
                    WebHostUrl           = config.WebHostUrl,
                    DefaultRootFileName  = DefaultRootFileName,
                    DefaultHandler       = debugDefaultHandler,
                };
            }

            NotFoundHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.NotFound);
            if (NotFoundHttpHandler == null)
            {
                NotFoundHttpHandler = new NotFoundHttpHandler
                {
                    IsIntegratedPipeline = IsIntegratedPipeline,
                    WebHostPhysicalPath  = WebHostPhysicalPath,
                    WebHostRootFileNames = WebHostRootFileNames,
                    WebHostUrl           = config.WebHostUrl,
                    DefaultRootFileName  = DefaultRootFileName,
                    DefaultHandler       = debugDefaultHandler,
                };
            }
        }
Exemplo n.º 15
0
        public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath)
        {
            var appHost = HostContext.AppHost;

            var pathParts = pathInfo.TrimStart('/').Split('/');

            if (pathParts.Length == 0)
            {
                return(NotFoundHttpHandler);
            }

            string contentType;
            var    restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType);

            if (restPath != null)
            {
                return new RestHandler {
                           RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType
                }
            }
            ;

            var existingFile         = pathParts[0];
            var matchesRootDirOrFile = appHost.Config.DebugMode
                ? appHost.VirtualFileSources.FileExists(existingFile) ||
                                       appHost.VirtualFileSources.DirectoryExists(existingFile)
                : WebHostRootFileNames.Contains(existingFile);

            if (matchesRootDirOrFile)
            {
                var fileExt = System.IO.Path.GetExtension(filePath);

                var isFileRequest = !string.IsNullOrEmpty(fileExt);

                if (!isFileRequest && !HostAutoRedirectsDirs)
                {
                    //If pathInfo is for Directory try again with redirect including '/' suffix
                    if (!pathInfo.EndsWith("/"))
                    {
                        var appFilePath = filePath.Substring(0, filePath.Length - requestPath.Length);
                        var redirect    = StaticFileHandler.DirectoryExists(filePath, appFilePath);
                        if (redirect)
                        {
                            return(new RedirectHttpHandler
                            {
                                RelativeUrl = pathInfo + "/",
                            });
                        }
                    }
                }

                //e.g. CatchAllHandler to Process Markdown files
                var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
                if (catchAllHandler != null)
                {
                    return(catchAllHandler);
                }

                if (!isFileRequest)
                {
                    return(appHost.VirtualFileSources.DirectoryExists(pathInfo)
                        ? StaticFilesHandler
                        : NotFoundHttpHandler);
                }

                return(ShouldAllow(requestPath)
                    ? StaticFilesHandler
                    : ForbiddenHttpHandler);
            }

            var handler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);

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

            if (appHost.Config.FallbackRestPath != null)
            {
                restPath = appHost.Config.FallbackRestPath(httpMethod, pathInfo, filePath);
                if (restPath != null)
                {
                    return(new RestHandler {
                        RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType
                    });
                }
            }

            return(null);
        }
        internal static void Init()
        {
            var appHost = HostContext.AppHost;

            WebHostPhysicalPath = appHost.VirtualFileSources.RootDirectory.RealPath;

            //Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources
            var hostedAtRootPath = appHost.Config.HandlerFactoryPath.IsNullOrEmpty();

//#if !NETSTANDARD2_0
//            //DefaultHttpHandler not supported in IntegratedPipeline mode
//            if (!Platform.IsIntegratedPipeline && HostContext.IsAspNetHost && !hostedAtRootPath && !Env.IsMono)
//                DefaultHttpHandler = new DefaultHttpHandler();
//#endif
            var rootFiles = appHost.VirtualFileSources.GetRootFiles();

            DefaultRootFileName = null;
            foreach (var file in rootFiles)
            {
                var fileNameLower = file.Name.ToLowerInvariant();
                if (DefaultRootFileName == null && appHost.Config.DefaultDocuments.Contains(fileNameLower))
                {
                    //Can't serve Default.aspx pages so ignore and allow for next default document
                    if (!fileNameLower.EndsWith(".aspx"))
                    {
                        DefaultRootFileName = file.Name;
                        StaticFileHandler.SetDefaultFile(file.VirtualPath, file.ReadAllBytes(), file.LastModified);

                        if (DefaultHttpHandler == null)
                        {
                            DefaultHttpHandler = new StaticFileHandler(file);
                        }
                    }
                }
            }

            if (!appHost.Config.DefaultRedirectPath.IsNullOrEmpty())
            {
                DefaultHttpHandler = new RedirectHttpHandler {
                    RelativeUrl = appHost.Config.DefaultRedirectPath
                }
            }
            ;

            var metadataHandler = new RedirectHttpHandler();

            if (!appHost.Config.MetadataRedirectPath.IsNullOrEmpty())
            {
                metadataHandler.RelativeUrl = appHost.Config.MetadataRedirectPath;
            }
            else
            {
                metadataHandler.RelativeUrl = "metadata";
            }
            if (hostedAtRootPath)
            {
                if (DefaultHttpHandler == null)
                {
                    DefaultHttpHandler = metadataHandler;
                }
            }
            else
            {
                DefaultHttpHandler = metadataHandler;
            }

            var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler;
            var debugDefaultHandler    = defaultRedirectHanlder?.RelativeUrl;

            ForbiddenHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden) ?? new ForbiddenHttpHandler
            {
                WebHostPhysicalPath = WebHostPhysicalPath,
                WebHostUrl          = appHost.Config.WebHostUrl,
                DefaultRootFileName = DefaultRootFileName,
                DefaultHandler      = debugDefaultHandler,
            };

            NotFoundHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.NotFound) ?? new NotFoundHttpHandler
            {
                WebHostPhysicalPath = WebHostPhysicalPath,
                WebHostUrl          = appHost.Config.WebHostUrl,
                DefaultRootFileName = DefaultRootFileName,
                DefaultHandler      = debugDefaultHandler,
            };
        }
        public static IServiceStackHandler GetHandlerForPathInfo(IHttpRequest httpReq, string filePath)
        {
            var appHost = HostContext.AppHost;

            var pathInfo   = httpReq.PathInfo;
            var httpMethod = httpReq.Verb;

            var pathParts = pathInfo.TrimStart('/').Split('/');

            if (pathParts.Length == 0)
            {
                return(NotFoundHttpHandler);
            }

            var restPath = RestHandler.FindMatchingRestPath(httpReq, out string contentType);

            if (restPath != null)
            {
                return new RestHandler {
                           RequestName = restPath.RequestType.GetOperationName()
                }
            }
            ;

            var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);

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

            var isFile      = httpReq.IsFile();
            var isDirectory = httpReq.IsDirectory();

            if (!isFile && !isDirectory && Env.IsMono)
            {
                isDirectory = StaticFileHandler.MonoDirectoryExists(filePath, filePath.Substring(0, filePath.Length - pathInfo.Length));
            }

            if (isFile || isDirectory)
            {
                //If pathInfo is for Directory try again with redirect including '/' suffix
                if (appHost.Config.RedirectDirectoriesToTrailingSlashes && isDirectory && !httpReq.OriginalPathInfo.EndsWith("/"))
                {
                    return new RedirectHttpHandler {
                               RelativeUrl = pathInfo + "/"
                    }
                }
                ;

                return(isDirectory || ShouldAllow(pathInfo)
                    ? StaticFilesHandler
                    : ForbiddenHttpHandler);
            }

            restPath = appHost.Config.FallbackRestPath?.Invoke(httpReq);
            if (restPath != null)
            {
                httpReq.SetRoute(restPath);
                return(new RestHandler {
                    RequestName = restPath.RequestType.GetOperationName()
                });
            }

            return(null);
        }
Exemplo n.º 18
0
        internal static void Init()
        {
            try
            {
#if !NETSTANDARD2_0
                //MONO doesn't implement this property
                var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline");
                if (pi != null)
                {
                    IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, TypeConstants.EmptyObjectArray);
                }
#endif
                var appHost = HostContext.AppHost;
                var config  = appHost.Config;

                var isAspNetHost = HostContext.IsAspNetHost;
                WebHostPhysicalPath = appHost.VirtualFileSources.RootDirectory.RealPath;

                //Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources
                var hostedAtRootPath = config.HandlerFactoryPath == null;

                //DefaultHttpHandler not supported in IntegratedPipeline mode
                if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono)
                {
                    DefaultHttpHandler = new DefaultHttpHandler();
                }

                var rootFiles = appHost.VirtualFileSources.GetRootFiles().ToList();
                foreach (var file in rootFiles)
                {
                    var fileNameLower = file.Name.ToLowerInvariant();
                    if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower))
                    {
                        //Can't serve Default.aspx pages so ignore and allow for next default document
                        if (!fileNameLower.EndsWith(".aspx"))
                        {
                            DefaultRootFileName = fileNameLower;
                            StaticFileHandler.SetDefaultFile(file.VirtualPath, file.ReadAllBytes(), file.LastModified);

                            if (DefaultHttpHandler == null)
                            {
                                DefaultHttpHandler = new StaticFileHandler(file);
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(config.DefaultRedirectPath))
                {
                    DefaultHttpHandler = new RedirectHttpHandler {
                        RelativeUrl = config.DefaultRedirectPath
                    };
                    NonRootModeDefaultHttpHandler = new RedirectHttpHandler {
                        RelativeUrl = config.DefaultRedirectPath
                    };
                }

                if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath))
                {
                    DefaultHttpHandler = new RedirectHttpHandler {
                        RelativeUrl = config.MetadataRedirectPath
                    };
                    NonRootModeDefaultHttpHandler = new RedirectHttpHandler {
                        RelativeUrl = config.MetadataRedirectPath
                    };
                }

                if (DefaultHttpHandler == null)
                {
                    DefaultHttpHandler = NotFoundHttpHandler;
                }

                var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler;
                var debugDefaultHandler    = defaultRedirectHanlder != null
                    ? defaultRedirectHanlder.RelativeUrl
                    : typeof(DefaultHttpHandler).GetOperationName();

                ForbiddenHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden);
                if (ForbiddenHttpHandler == null)
                {
                    ForbiddenHttpHandler = new ForbiddenHttpHandler
                    {
                        IsIntegratedPipeline = IsIntegratedPipeline,
                        WebHostPhysicalPath  = WebHostPhysicalPath,
                        WebHostUrl           = config.WebHostUrl,
                        DefaultRootFileName  = DefaultRootFileName,
                        DefaultHandler       = debugDefaultHandler,
                    };
                }

                NotFoundHttpHandler = appHost.GetCustomErrorHttpHandler(HttpStatusCode.NotFound);
                if (NotFoundHttpHandler == null)
                {
                    NotFoundHttpHandler = new NotFoundHttpHandler
                    {
                        IsIntegratedPipeline = IsIntegratedPipeline,
                        WebHostPhysicalPath  = WebHostPhysicalPath,
                        WebHostUrl           = config.WebHostUrl,
                        DefaultRootFileName  = DefaultRootFileName,
                        DefaultHandler       = debugDefaultHandler,
                    };
                }
            }
            catch (Exception ex)
            {
                HostContext.AppHost.OnStartupException(ex);
            }
        }
        public void SetDefaultValues(ServerOption option)
        {
            if (option == null)
            {
                throw new ArgumentNullException(nameof(option));
            }

            if (option.HttpListenerOptions != null)
            {
                foreach (var a in option.HttpListenerOptions)
                {
                    if (string.IsNullOrEmpty(a.Ip))
                    {
                        a.Ip = "*";
                    }

                    // 端口号为 0 表示使用动态端口
                    if (a.Port == 0)
                    {
                        // 这里不检查返回值,因为不太可能把端口全部用完
                        a.Port = NetHelper.GetFreeTcpPort(5000, 50000);
                    }
                }
            }


            if (option.Website != null)
            {
                option.Website.LocalPath = Path.GetFullPath(option.Website.LocalPath);

                if (option.Website.CacheDuration <= 0)
                {
                    option.Website.CacheDuration = 3600 * 24 * 365;      // 默认缓存1年
                }
                if (option.Website.StaticFiles != null)
                {
                    foreach (var f in option.Website.StaticFiles)
                    {
                        if (f.Cache == 0)
                        {
                            f.Cache = option.Website.CacheDuration;      // 取默认缓存值
                        }
                        if (string.IsNullOrEmpty(f.Mine))
                        {
                            f.Mine = StaticFileHandler.GetMimeType(f.Ext);
                        }
                    }
                }
            }

            if (option.Modules != null)
            {
                option.ModuleTypes = (from s in option.Modules
                                      let t = Type.GetType(s, false, false)
                                              select t
                                      ).ToArray();
            }

            if (option.Handlers != null)
            {
                option.HandlerTypes = (from s in option.Handlers
                                       let t = Type.GetType(s, false, false)
                                               select t
                                       ).ToArray();
            }
        }
Exemplo n.º 20
0
        public static IHttpHandler GetHandlerForPathInfo(IHttpRequest httpReq, string filePath)
        {
            var appHost = HostContext.AppHost;

            var pathInfo   = httpReq.PathInfo;
            var httpMethod = httpReq.Verb;

            if (pathInfo.AsSpan().TrimStart('/').Length == 0)
            {
                return(NotFoundHttpHandler);
            }

            var restPath = RestHandler.FindMatchingRestPath(httpReq, out var contentType);

            if (restPath != null)
            {
                return new RestHandler {
                           RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType
                }
            }
            ;

            var catchAllHandler = GetCatchAllHandlerIfAny(appHost, httpMethod, pathInfo, filePath);

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

            var isFile      = httpReq.IsFile();
            var isDirectory = httpReq.IsDirectory();

            if (!isFile && !isDirectory && Env.IsMono)
            {
                isDirectory = StaticFileHandler.MonoDirectoryExists(filePath, filePath.Substring(0, filePath.Length - pathInfo.Length));
            }

            if (isFile || isDirectory)
            {
                //If pathInfo is for Directory try again with redirect including '/' suffix
                if (appHost.Config.RedirectDirectoriesToTrailingSlashes && isDirectory && !httpReq.OriginalPathInfo.EndsWith("/"))
                {
                    return new RedirectHttpHandler {
                               RelativeUrl = pathInfo + "/"
                    }
                }
                ;

                if (isDirectory)
                {
                    return(StaticFilesHandler);
                }

                return(ShouldAllow(pathInfo)
                    ? StaticFilesHandler
                    : ForbiddenHttpHandler);
            }

            // Check for PagedBasedRouting before wildcard Fallback Service
            foreach (var httpHandlerResolver in appHost.FallbackHandlersArray)
            {
                var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath);
                if (httpHandler != null)
                {
                    return(httpHandler);
                }
            }

            if (appHost.Config.FallbackRestPath != null)
            {
                restPath = appHost.Config.FallbackRestPath(httpReq);
                if (restPath != null)
                {
                    return new RestHandler {
                               RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType
                    }
                }
                ;
            }

            return(null);
        }