示例#1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new Microsoft.AspNetCore.SpaServices.Webpack.WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }

            // Enable LESS files. If we don't care about them, we can just use app.UseStaticFiles().
            var contentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            contentTypeProvider.Mappings[".less"] = "text/css";

            app.UseStaticFiles(new StaticFileOptions()
            {
                ContentTypeProvider = contentTypeProvider
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
示例#2
0
        public FileStreamResult DownLoad([FromServices] IWebHostEnvironment environment, string FileID)
        {
            //try
            //{
            var userSession = _tokenManager.GetSessionInfo();

            if (string.IsNullOrEmpty(FileID))
            {
                throw new Exception("文件ID不允许为空");
            }
            gnl_File file = _gnlfileService.GetId(FileID);

            if (file == null)
            {
                throw new Exception("文件不存在");
            }
            string filepath = file.AbsoluteFilePath;
            var    stream   = System.IO.File.OpenRead(filepath);
            string fileExt  = file.FileExt; // 这里可以写一个获取文件扩展名的方法,获取扩展名
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];
            var fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName);

            _gnlfileService.Update(f => f.FileID.ToString() == FileID, f => new gnl_File {
                DownloadCount = file.DownloadCount + 1
            });

            return(File(stream, memi, fileName));
            //}
            //catch(Exception ex)
            //{
            //return toResponse(StatusCodeType.Error, ex.Message);
            //}
        }
示例#3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            // Use static files
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            provider.Mappings[".properties"] = "text/plain";
            app.UseStaticFiles(new StaticFileOptions {
                ContentTypeProvider = provider
            });

            // Use and redirect to HTTPS and
            app.UseRewriter(new RewriteOptions().AddRedirectToHttps(301, 443));
            app.UseHttpsRedirection();
            app.UseHsts();

            // Use authentication
            app.UseAuthentication();

            // Use mvc
            app.UseMvc();
        }
示例#4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            provider.Mappings[".data"] = "";

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
                RequestPath         = "",
                ContentTypeProvider = provider
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapHub <ServerlistHub>("/serverlistHub");
                endpoints.MapHub <ServerHub>("/serverHub");
            });
        }
示例#5
0
            /// <summary>
            ///     Handle
            /// </summary>
            /// <param name="query"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public async Task <QueryResponse> Handle(DownloadQuery query, CancellationToken cancellationToken)
            {
                QueryResponse response = new QueryResponse();
                Stream        ms       = new MemoryStream();

                try
                {
                    ms = await _storageService.GetFileStream(query.FilePath);

                    ms.Position = 0; // Have to reset the current position
                }
                catch (Exception ex)
                {
                    // Exception and logging are handled in a centralized place, see ApiExceptionFilter.
                    throw new EntityNotFoundException(nameof(AttachmentModel), query.FilePath);
                }

                // Content Type mapping
                string[] fileNameParts = query.FilePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
                string   fileName      = fileNameParts[fileNameParts.Length - 1];

                var    contentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
                string contentType         = "application/octet-stream";

                if (!contentTypeProvider.TryGetContentType(fileName, out contentType))
                {
                    contentType = "application/octet-stream"; // fallback
                }

                response.FileName    = String.IsNullOrEmpty(query.OriginalFileName) ? fileName : query.OriginalFileName;
                response.Stream      = ms;
                response.ContentType = contentType;

                return(response);
            }
示例#6
0
        public FileStreamResult DownBmd(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return(null);
            }
            // 前端 blob 接收,具体查看前端admin代码
            string filepath = Path.Combine(_env.WebRootPath, Path.GetFileName(filename));

            if (System.IO.File.Exists(filepath))
            {
                var stream = System.IO.File.OpenRead(filepath);
                //string fileExt = ".bmd";
                //获取文件的ContentType
                var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
                //var memi = provider.Mappings[fileExt];
                var fileName = Path.GetFileName(filepath);

                HttpContext.Response.Headers.Add("fileName", fileName);

                return(File(stream, "application/octet-stream", fileName));
            }
            else
            {
                return(null);
            }
        }
示例#7
0
        public FileStreamResult Download([FromServices] IWebHostEnvironment environment, string fileName = "")
        {
            string filepath            = Path.Combine(environment.WebRootPath, "images", fileName);
            var    stream              = System.IO.File.OpenRead(filepath);
            string fileExt             = Path.GetExtension(filepath);
            var    contentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var    contentType         = contentTypeProvider.Mappings[fileExt];
            var    fileDownloadName    = Path.GetFileName(filepath);

            return(File(stream, contentType, fileDownloadName));
        }
示例#8
0
        /// <summary>
        /// Attempts to intelligently guess the content mime type from the file name
        /// </summary>
        public static string ContentType(string fileName)
        {
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            if (!provider.TryGetContentType(fileName, out string contentType))
            {
                contentType = "application/octet-stream";
            }

            return(contentType);
        }
示例#9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(AllException);
            }

            app.UseIgnoreUrl("Views");

            app.UseResponseCompression();

            // 此部分为作者需要,你们可以直接删掉
            var staticfile = new StaticFileOptions();
            var provider   = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            provider.Mappings.Add(".php", "text/plain");//手动设置对应MIME
            provider.Mappings.Add(".aspx", "text/plain");
            staticfile.ContentTypeProvider = provider;
            //staticfile.OnPrepareResponse = (a) =>
            //{

            //};
            app.UseStaticFiles(staticfile);

            app.UseDiySession();

            app.UseAshx(routes =>
            {
                routes.MapApiRoute(
                    name: "Api",
                    areaName: "AdminCore.Api",
                    template: "Api/{controller=AdminServers}/{action}/{id?}");

                routes.MapApiRoute(
                    name: "Admin",
                    areaName: "AdminCore.WebUi",
                    template: "{controller=Admin}/{action=Index}/{id?}");
            });

            FacadeManage.UseSqlLog(loggerFactory); //注册相关SQL日志。

            Menu.Reload();                         //获取默认系统菜单

            TcpFrame.ConnectClient(loggerFactory);

            app.GetObject <UpLoad>().SetBasePath(env.WebRootPath);

            Api.AdminServers.StartBaseLog();
        }
示例#10
0
        private string GetMimeType(string fileName)
        {
            // Make Sure Microsoft.AspNetCore.StaticFiles Nuget Package is installed
            var    provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            string contentType;

            if (!provider.TryGetContentType(fileName, out contentType))
            {
                contentType = "application/octet-stream";
            }
            return(contentType);
        }
示例#11
0
        /// <summary>
        /// 附件下载
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public IActionResult DownLoad(string file)
        {
            var addrUrl = file;
            //转换成文件流
            var stream = System.IO.File.OpenRead(addrUrl);
            //获取文件的后缀名
            string fileExt = Path.GetExtension(addrUrl);
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];

            return(File(stream, memi, Path.GetFileName(addrUrl)));
        }
示例#12
0
        public FileStreamResult DownloadPicture([FromServices] IWebHostEnvironment environment)
        {
            string foldername = "images";
            string filepath   = Path.Combine(environment.WebRootPath, foldername, "20201112145833764.jpeg");
            var    stream     = System.IO.File.OpenRead(filepath);
            string fileExt    = ".jpg"; // 这里可以写一个获取文件扩展名的方法,获取扩展名
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];
            var fileName = Path.GetFileName(filepath);

            return(File(stream, memi, fileName));
        }
示例#13
0
        public FileStreamResult DownImg()
        {
            var    addrUrl = Directory.GetCurrentDirectory() + "\\微信截图_20190304212953.png";
            var    stream  = System.IO.File.OpenRead(addrUrl);
            string fileExt = ".jpg";  // 这里可以写一个获取文件扩展名的方法,获取扩展名
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];
            var fileName = Path.GetFileName(addrUrl);


            return(File(stream, memi, fileName));
        }
        public FileStreamResult FileDownload(FileDownloadDto fileDto, [FromServices] IWebHostEnvironment environment)
        {
            string foldername = "";
            string filepath   = Path.Combine(environment.WebRootPath, fileDto.FileUrl);
            var    stream     = System.IO.File.OpenRead(filepath);
            string fileExt    = fileDto.FileUrl.Substring(fileDto.FileUrl.LastIndexOf('.')); // 这里可以写一个获取文件扩展名的方法,获取扩展名
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];
            var fileName = Path.GetFileName(filepath);

            return(File(stream, memi, HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"))));
        }
示例#15
0
文件: Startup.cs 项目: cipherRex/BotB
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseResponseCompression();

            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            //provider.Mappings.Add(".wasm", "application/octet-stream");
            provider.Mappings.Add(".unityweb", "application/octet-stream");

            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider,
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();

            //new:
            //app.UsePathBase("/BridgeBrawl");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapHub <ChatHub>("/chathub");
                endpoints.MapFallbackToFile("index.html");
            });

            //new:
            //app.UsePathBase("/BridgeBrawl/");
        }
示例#16
0
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime)
        {
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".ps1"]  = "text/plain";
            provider.Mappings[".psm1"] = "text/plain";
            provider.Mappings[".psd1"] = "text/plain";
            provider.Mappings[".log"]  = "text/plain";
            provider.Mappings[".yml"]  = "text/plain";

            loggerFactory.AddNLog();
            app.UseResponseCompression();
            app.UseStatusCodePagesWithReExecute("/redirect/{0}");
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider          = new PhysicalFileProvider(env.ContentRootPath),
                RequestPath           = new PathString(""),
                ServeUnknownFileTypes = true,
                ContentTypeProvider   = provider
            });

            var dashboardService = app.ApplicationServices.GetService(typeof(IDashboardService)) as IDashboardService;

            if (dashboardService?.DashboardOptions?.PublishedFolders != null)
            {
                foreach (var publishedFolder in dashboardService.DashboardOptions.PublishedFolders)
                {
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        RequestPath           = publishedFolder.RequestPath,
                        FileProvider          = new PhysicalFileProvider(publishedFolder.Path),
                        ServeUnknownFileTypes = true,
                        ContentTypeProvider   = provider
                    });
                }
            }

            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());

            app.UseSignalR(routes =>
            {
                routes.MapHub <DashboardHub>("/dashboardhub");
            });
            app.UseWebSockets();

            app.UseSession();

            app.UseMvc();
        }
示例#17
0
        public FileStreamResult DownImg([FromServices] IHostingEnvironment environment)
        {
            string foldername = "";
            string filepath   = Path.Combine(environment.WebRootPath, foldername, "测试下载中文名称的图片.png");
            var    stream     = System.IO.File.OpenRead(filepath);
            string fileExt    = ".jpg"; // 这里可以写一个获取文件扩展名的方法,获取扩展名
            //获取文件的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];
            var fileName = Path.GetFileName(filepath);


            return(File(stream, memi, fileName));
        }
示例#18
0
文件: Deploy.cs 项目: aTiKhan/Vidyano
        static string GetContentType(string file)
        {
            if (file.EndsWith(".ts"))
            {
                return("text/x.typescript");
            }

            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            if (!provider.TryGetContentType(file, out var contentType))
            {
                contentType = "application/octet-stream";
            }

            return(contentType);
        }
        /// <summary>
        /// Crea una respuesta de devolución de fichero
        /// </summary>
        /// <param name="file">Array de bytes del fichero</param>
        /// <param name="fileName">Nombre del fichero</param>
        /// <returns></returns>
        public static IActionResult CreateFileResponse(byte[] file, string fileName)
        {
            var    provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            string contentType;

            if (!provider.TryGetContentType(fileName, out contentType))
            {
                contentType = "application/octet-stream";
            }

            return(new FileContentResult(file, contentType)
            {
                FileDownloadName = fileName,
                LastModified = DateTime.Now
            });
        }
示例#20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseStatusCodePagesWithReExecute("/Status/Status{0}");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=86400";
                }
            });

            {
                // Remove this next one for ASP.NET Core upgrade - https://github.com/aspnet/AspNetCore/issues/2442
                var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
                provider.Mappings[".webmanifest"] = "application/json";
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider        = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
                    RequestPath         = "",
                    ContentTypeProvider = provider
                });
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDynamicPageRoute <StaticPageRouteValueTransformer>("{uriSegment}");
                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });
        }
        public IActionResult DownloadFile(string name)
        {
            // var ffile =await _UnitOfWork.Requests.GetAsync(id);

            string FilePath = Path.Combine(_enviroment.WebRootPath, "image/Document") + $@"\{name}";

            //string FileName = $"{name.Name}.{name.Type}";
            string FileName = $"{name}";

            var fileProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            if (!fileProvider.TryGetContentType(FilePath, out string contentType))
            {
                throw new ArgumentOutOfRangeException($"Unable to find Content Type for file name {FilePath}.");
            }

            byte[] file = System.IO.File.ReadAllBytes(FilePath);//به بایت تبدیل کن
            return(File(file, contentType, fileDownloadName: FileName));
        }
示例#22
0
        // This method gets caller by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseWebSockets();

            {
                var          ctp         = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
                const string octetStream = "application/octet-stream";
                /* need these ones for Mono wasm */
                ctp.Mappings[".dll"]  = octetStream;
                ctp.Mappings[".blat"] = octetStream;
                ctp.Mappings[".dat"]  = octetStream;
                /* FIXME: these three are not needed but the sample bundles some */
                ctp.Mappings[".dmeta"] = octetStream;
                ctp.Mappings[".dil"]   = octetStream;
                ctp.Mappings[".dpdb"]  = octetStream;
                var fs = new FileServerOptions();
                fs.DefaultFilesOptions.DefaultFileNames = new string[] { "index.html" };
                fs.EnableDirectoryBrowsing = true;
                fs.StaticFileOptions.ContentTypeProvider = ctp;
                app.UseFileServer(fs);
            }

            app.UseRouting();

            app.UseHotReloadInjector();

            // app.UseEndpoints(endpoints =>
            // {
            //     endpoints.MapGet("/hw", async context =>
            //     {
            //         await context.Response.WriteAsync("Hello World!");
            //     });
            // });
        }
示例#23
0
        public void ConfigureStaticFiles(IApplicationBuilder app)
        {
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".json"] = "text/json";
            StaticFileOptions sfo = new StaticFileOptions()
            {
                ContentTypeProvider = provider
            };

            app.UseStaticFiles(sfo);

            var fso = new FileServerOptions {
                FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "articles")),
                RequestPath             = "/articles",
                EnableDirectoryBrowsing = false
            };

            fso.StaticFileOptions.ContentTypeProvider = provider;
            app.UseFileServer(fso);
        }
示例#24
0
        public static string getMimeTypeFromExtension(string extension, string failoverMime = "application/octet-stream")
        {
            bool   identified;
            string fileName, fileMime;

            Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider extensionContentTypeProvider;

            extensionContentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            extensionContentTypeProvider.Mappings.Add(".exe", "application/vnd.microsoft.portable-executable");


            fileName = "basename." + extension.TrimStart('.');

            identified = (extensionContentTypeProvider.TryGetContentType(fileName, out fileMime));

            if (identified)
            {
                return(fileMime);
            }
            else
            {
                return(failoverMime);
            }
        }
示例#25
0
        public IActionResult GetImage(string id, string temp, string temp1)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(null);
            }

            var file = System.IO.Path.Combine(_destination, id);

            var    provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            string contentType;

            if (!provider.TryGetContentType(file, out contentType))
            {
                contentType = "application/octet-stream";
            }

            if (System.IO.File.Exists(file))
            {
                return(File(new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read), contentType));
            }

            return(null);
        }
示例#26
0
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime)
        {
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".ps1"]  = "text/plain";
            provider.Mappings[".psm1"] = "text/plain";
            provider.Mappings[".psd1"] = "text/plain";
            provider.Mappings[".log"]  = "text/plain";
            provider.Mappings[".yml"]  = "text/plain";

            loggerFactory.AddNLog();
            app.UseResponseCompression();
            app.UseStatusCodePages(async context => {
                if (context.HttpContext.Response.StatusCode == 404 && !context.HttpContext.Request.Path.StartsWithSegments("/api"))
                {
                    var fileName = context.HttpContext.Request.Path.ToString().Split('/').Last();
                    var asset    = AssetService.Instance.FindAsset(fileName);
                    if (asset != null)
                    {
                        var response        = context.HttpContext.Response;
                        response.StatusCode = 200;
                        var file            = File.ReadAllBytes(asset);
                        await response.Body.WriteAsync(file, 0, file.Length);
                    }
                    else
                    {
                        var response         = context.HttpContext.Response;
                        response.StatusCode  = 200;
                        var filePath         = env.ContentRootPath + "/index.html";
                        response.ContentType = "text/html; charset=utf-8";
                        var file             = File.ReadAllText(filePath);
                        await response.WriteAsync(file);
                    }
                }
                else
                {
                    await context.Next(context.HttpContext);
                }
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider          = new PhysicalFileProvider(env.ContentRootPath),
                RequestPath           = new PathString(""),
                ServeUnknownFileTypes = true,
                ContentTypeProvider   = provider
            });

            var dashboardService = app.ApplicationServices.GetService(typeof(IDashboardService)) as IDashboardService;

            if (dashboardService?.DashboardOptions?.Certificate != null || dashboardService?.DashboardOptions?.CertificateFile != null)
            {
                if (dashboardService.DashboardOptions.Port == dashboardService.DashboardOptions.HttpsPort)
                {
                    Logger.Warn("Port and HTTPS port are the same. HTTPS Redirection will not work. Select two different ports.");
                }
                else
                {
                    app.UseHttpsRedirection();
                }
            }

            if (dashboardService?.DashboardOptions?.PublishedFolders != null)
            {
                foreach (var publishedFolder in dashboardService.DashboardOptions.PublishedFolders)
                {
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        RequestPath           = publishedFolder.RequestPath,
                        FileProvider          = new PhysicalFileProvider(publishedFolder.Path),
                        ServeUnknownFileTypes = true,
                        ContentTypeProvider   = provider
                    });
                }
            }

            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());

            app.UseSignalR(routes =>
            {
                routes.MapHub <DashboardHub>("/dashboardhub");
            });

            app.UseWebSockets();

            app.UseSession();

            app.UseMvc();
        }
示例#27
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory)
        {
            #region *** Logging ***

            // Add NLog as logging provider. NLog config is set in Program.Main()
            // see: https://github.com/NLog/NLog/issues/2859
            app.ApplicationServices.SetupNLogServiceLocator();

            // Allow TournamentManager to make use of Microsoft.Extensions.Logging
            TournamentManager.AppLogging.Configure(loggerFactory);

            #endregion

            #region *** Rewrite ALL domains (even those without SSL certificate) to https://volleyball-liga.de ***

            {
                using var iisUrlRewriteStreamReader = File.OpenText(Path.Combine(WebHostEnvironment.ContentRootPath, Program.ConfigurationFolder, @"IisRewrite.config"));
                var options = new RewriteOptions().AddIISUrlRewrite(iisUrlRewriteStreamReader);
                app.UseRewriter(options);
            }

            #endregion

            if (env.IsDevelopment())
            {
                app.UseMiddleware <StackifyMiddleware.RequestTracerMiddleware>();
                // Turn production error behavior on=false/off=true
                if (true)
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStatusCodePages();
                }
                else
                {
                    app.UseStatusCodePagesWithReExecute($"/{nameof(Controllers.Error)}/{{0}}");
                    app.UseExceptionHandler($"/{nameof(Controllers.Error)}/500");
                }
            }
            else
            {
                app.UseStatusCodePagesWithReExecute($"/{nameof(Controllers.Error)}/{{0}}");
                app.UseExceptionHandler($"/{nameof(Controllers.Error)}/500");
                // instruct the browsers to always access the site via HTTPS
                app.UseHsts();
            }

            #region *** JsNLog ***
            // add the JSNLog middleware before the UseStaticFiles middleware.
            var jsNLogConfiguration =
                new JsnlogConfiguration
            {
                loggers = new List <Logger>
                {
                    new Logger {
                        name = "JsLogger"
                    }
                }
            };
            app.UseJSNLog(new LoggingAdapter(loggerFactory), jsNLogConfiguration);
            #endregion

            app.UseHttpsRedirection();

            #region *** Static files ***
            // For static files in the wwwroot folder
            app.UseDefaultFiles();

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    var headers          = ctx.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromDays(30)
                    };
                }
            });
            // For static files using a content type provider:
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            // Make sure .webmanifest files don't cause a 404
            provider.Mappings[".webmanifest"] = "application/manifest+json";
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider,
                OnPrepareResponse   = ctx =>
                {
                    var headers          = ctx.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromDays(30)
                    };
                }
            });
            #endregion

            app.UseCookiePolicy();

            // Must be before UseMvc to avoid InvalidOperationException
            app.UseSession();

            if (bool.Parse(Configuration.GetSection("CultureInfo:CulturePerRequest").Value))
            {
                app.UseRequestLocalization(); // options are defined in services
            }
            app.UseRouting();

            // UseAuthentication and UseAuthorization: after UseRouting and UseCors, but before UseEndpoints
            app.UseAuthentication();
            app.UseAuthorization();

            /* Before using endpoint routing, all anchor, form tags Url.(...) and RedirectToAction(...) tag helpers had to be updated with {organization}
             * (ViewContext.RouteData.Values["organization"]) because ambient parameters are not preserved here (as opposed to IRoute) */
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            #region *** Initialize ranking tables and charts ***

            var siteList = app.ApplicationServices.GetRequiredService <SiteList>();
            var queue    = app.ApplicationServices.GetRequiredService <IBackgroundQueue>();

            foreach (var orgSite in siteList.Where(ctx => !string.IsNullOrEmpty(ctx.OrganizationKey)))
            {
                var siteContext       = new SiteContext(orgSite.OrganizationKey, app.ApplicationServices.GetRequiredService <OrganizationContextResolver>(), siteList);
                var rankingUpdateTask = app.ApplicationServices.GetRequiredService <RankingUpdateTask>();
                rankingUpdateTask.SiteContext  = siteContext.Resolve(orgSite.OrganizationKey);
                rankingUpdateTask.TournamentId = siteContext.MatchResultTournamentId;
                rankingUpdateTask.Timeout      = TimeSpan.FromMinutes(5);
                queue.QueueTask(rankingUpdateTask);
            }

            #endregion
        }
示例#28
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/></param>
        /// <param name="env">The <see cref="IWebHostEnvironment"/></param>
        /// <param name="api">The PiranhaCms <see cref="IApi"/></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApi api)
        {
            var cultureInfo = new System.Globalization.CultureInfo("de-DE");

            System.Globalization.CultureInfo.DefaultThreadCurrentCulture   =
                System.Globalization.CultureInfo.CurrentCulture            = cultureInfo;
            System.Globalization.CultureInfo.DefaultThreadCurrentUICulture =
                System.Globalization.CultureInfo.CurrentCulture            = cultureInfo;

            if (false)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithReExecute($"/Error/{{0}}");
                app.UseExceptionHandler($"/Error/500");
                // instruct the browsers to always access the site via HTTPS
                app.UseHsts();
            }

            // Initialize Piranha
            App.Init(api);

            // Build all content types in this assembly
            new ContentTypeBuilder(api)
            .AddAssembly(typeof(Startup).Assembly)
            .Build()
            .DeleteOrphans();

            // Register custom blocks
            App.Blocks.Register <PersonProfileBlock>();

            /* To build specific types:
             * new Piranha.AttributeBuilder.PageTypeBuilder(api)
             *  .AddType(typeof(Models.BlogArchive))
             *  .AddType(typeof(Models.StandardPage))
             *  .AddType(typeof(Models.TeaserPage))
             *  .Build()
             *  .DeleteOrphans();
             * new Piranha.AttributeBuilder.PostTypeBuilder(api)
             *  .AddType(typeof(Models.BlogPost))
             *  .Build()
             *  .DeleteOrphans();
             * new Piranha.AttributeBuilder.SiteTypeBuilder(api)
             *  .AddType(typeof(Models.StandardSite))
             *  .Build()
             *  .DeleteOrphans();
             */

            // Configure Tiny MCE
            EditorConfig.FromFile($@"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{Program.ConfigurationFolder}{Path.DirectorySeparatorChar}editorconfig.json");

            // Keep before .UsePiranha()
            app.UseSession();

            #region *** Rewrite domains (even those without SSL certificate) to https://www.volleyballclub.de ***

            app.UseRewriter(new RewriteOptions()
                            .AddRedirectToWwwPermanent()
                            .AddRedirectToHttpsPermanent()
                            );

            #endregion

            // Middleware setup
            app.UsePiranha(options =>
            {
                options.UseManager();
                options.UseTinyMCE();
                options.UseIdentity();
            });

            // For static files using a content type provider:
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            // Make sure .webmanifest files don't cause a 404
            provider.Mappings[".webmanifest"] = "application/manifest+json";
            app.UseStaticFiles(new StaticFileOptions {
                ContentTypeProvider = provider,
                OnPrepareResponse   = ctx =>
                {
                    var headers          = ctx.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue {
                        Public = true,
                        MaxAge = TimeSpan.FromDays(5)
                    };
                }
            });
        }
示例#29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IApplicationLifetime lifetime,
            IHostingEnvironment env,
#if SERVE_REMOTING
            BlackMaple.MachineWatch.RemotingServer machServer,
#endif
            Controllers.WebsocketManager wsManager)
        {
            app.UseResponseCompression();
            app.UseCors(builder => builder
                        .WithOrigins(
                            _fmsSt.AdditionalLogServers
#if DEBUG
                            .Concat(new[] { "http://localhost:1234" }) // parcel bundler url
#endif
                            .ToArray()
                            )
#if DEBUG
                        .WithMethods(new[] { "GET", "PUT", "POST", "DELETE" })
#else
                        .WithMethods("GET")
#endif
                        .WithHeaders("content-type", "authorization")
                        );
            app.UseMiddleware(typeof(ErrorHandlingMiddleware));
            if (_serverSt.UseAuthentication)
            {
                app.UseAuthentication();
            }
            app.UseMvc();

            // https://github.com/aspnet/Home/issues/2442
            var fileExt = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            fileExt.Mappings[".webmanifest"] = "application/manifest+json";
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = fileExt
            });

            if (!string.IsNullOrEmpty(_fmsSt.InstructionFilePath))
            {
                if (System.IO.Directory.Exists(_fmsSt.InstructionFilePath))
                {
                    app.UseStaticFiles(new StaticFileOptions()
                    {
                        FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(_fmsSt.InstructionFilePath),
                        RequestPath  = "/instructions"
                    });
                }
                else
                {
                    Log.Error("Instruction directory {path} does not exist or is not a directory", _fmsSt.InstructionFilePath);
                }
            }

            if (!string.IsNullOrEmpty(_serverSt.TLSCertFile))
            {
                if (!env.IsDevelopment())
                {
                    app.UseHsts();
                }
                app.UseHttpsRedirection();
            }

            app.UseWebSockets();
            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/api/v1/events")
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        if (_serverSt.UseAuthentication)
                        {
                            var res = await context.AuthenticateAsync();
                            if (res.Failure != null)
                            {
                                context.Response.StatusCode = 401;
                                return;
                            }
                        }
                        var ws = await context.WebSockets.AcceptWebSocketAsync();
                        await wsManager.HandleWebsocket(ws);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else
                {
                    await next();
                }
            });

            app
            .UseSwagger(settings =>
            {
                settings.PostProcess = (doc, req) =>
                {
                    doc.Host     = null;
                    doc.BasePath = null;
                    doc.Schemes  = null;
                };
            })
            .UseSwaggerUi3();

            app.Run(async context =>
            {
                context.Response.ContentType = "text/html";
                await context.Response.SendFileAsync(System.IO.Path.Combine(env.WebRootPath, "index.html"));
            });

            lifetime.ApplicationStopping.Register(async() =>
            {
                if (_fmsImpl == null)
                {
                    return;
                }
                await wsManager.CloseAll();
                foreach (var w in _fmsImpl.Workers)
                {
                    w.Dispose();
                }
                _fmsImpl.Backend?.Dispose();
            });

#if SERVE_REMOTING
            if (_serverSt.EnableSailAPI)
            {
                lifetime.ApplicationStopping.Register(() => {
                    machServer.Dispose();
                });
            }
#endif
        }