Exemplo n.º 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();
            }

            var path = Path.Combine(env.ContentRootPath); 
            var provider = new PhysicalFileProvider(path);
            provider.Watch("*.*");

            // Set up custom content types -associating file extension to MIME type
            var contentTypeProvider = new FileExtensionContentTypeProvider();
            // Add new mappings
            contentTypeProvider.Mappings[".hdr"] = "application/octet-stream";
            contentTypeProvider.Mappings[".babylon"] = "application/json";
            contentTypeProvider.Mappings[".fx"] = "text/plain";
            contentTypeProvider.Mappings[".map"] = "text/plain";

            var options = new StaticFileOptions()
            {
                RequestPath = "",
                FileProvider = provider,
                ContentTypeProvider = contentTypeProvider
            };
            app.UseStaticFiles(options);
        }
        // <Services
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // >Configure
        public void Configure(IApplicationBuilder app)
        {
            // Set up custom content types -associating file extension to MIME type
            var provider = new FileExtensionContentTypeProvider();
            // Add new mappings
            provider.Mappings[".myapp"] = "application/x-msdownload";
            provider.Mappings[".htm3"] = "text/html";
            provider.Mappings[".image"] = "image/png";
            // Replace an existing mapping
            provider.Mappings[".rtf"] = "application/x-msdownload";
            // Remove MP4 videos.
            provider.Mappings.Remove(".mp4");

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/MyImages"),
                ContentTypeProvider = provider
            });

            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/MyImages")
            });
        }
Exemplo n.º 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, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            // app.UseDefaultFiles();

            // Code removed for brevity.

            // Set up custom content types -associating file extension to MIME type
            var provider = new FileExtensionContentTypeProvider();
            // Add new mappings
            provider.Mappings[".myapp"] = "application/x-msdownload";
            provider.Mappings[".htm3"] = "text/html";
            provider.Mappings[".image"] = "image/png";
            // Replace an existing mapping
            provider.Mappings[".rtf"] = "application/x-msdownload";
            // Remove MP4 videos.
            provider.Mappings.Remove(".mp4");

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/MyImages"),
                ContentTypeProvider = provider
            });

            app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
                RequestPath = new PathString("/MyImages")
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        }
Exemplo n.º 4
0
        public ActionResult GetTexture(string scene, string name)
        {
            var file = $"Assets/{scene}/{name}";

            if (!System.IO.File.Exists(file))
            {
                return(NotFound());
            }

            var    provider = new FileExtensionContentTypeProvider();
            string contentType;

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

            var fi = new FileInfo(file);

            return(File(fi.OpenRead(), contentType));
        }
Exemplo n.º 5
0
        private static StaticFileOptions CreateStaticFileOptions()
        {
            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings[".webmanifest"] = "application/manifest+json";

            return(new StaticFileOptions()
            {
                ContentTypeProvider = provider,
                DefaultContentType = "application/json",
                ServeUnknownFileTypes = true,
                OnPrepareResponse = (context) =>
                {
                    var headers = context.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue()
                    {
                        MaxAge = TimeSpan.FromDays(7)
                    };
                }
            });
        }
Exemplo n.º 6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var provider = new FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".mtl"]  = "application/octet-stream"; // "text /xml";
            provider.Mappings[".obj"]  = "application/octet-stream"; // "text /xml";
            provider.Mappings[".patt"] = "application/octet-stream"; // "text /xml";
            provider.Mappings[".png"]  = "image/png";                //image / png
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
                RequestPath         = "",
                ContentTypeProvider = provider
            });
            var options = new RewriteOptions().AddRedirectToHttps(StatusCodes.Status301MovedPermanently, 63423);

            app.UseRewriter(options);
            app.UseMvc();
        }
Exemplo n.º 7
0
        public IActionResult NoFoundImage()
        {
            string path;

            if (RuntimeEnvironment.Islinux)
            {
                //图片来自网络
                path = "upload/404.jpg";
            }
            else
            {
                path = "upload\\404.jpg";
            }
            var    stream  = System.IO.File.OpenRead(path);
            string fileExt = Path.GetExtension("404.jpg");
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];

            return(File(stream, memi));
        }
Exemplo n.º 8
0
        public ActionResult GetFile([FromQuery] string fileName)
        {
            var rootPath = Directory.GetCurrentDirectory();

            var filePath = $"{rootPath}/FileToDownloadForLoggedUser/{fileName}";

            var isExist = System.IO.File.Exists(filePath);

            if (!isExist)
            {
                return(NotFound());
            }

            var contentProvider = new FileExtensionContentTypeProvider();

            contentProvider.TryGetContentType(filePath, out string fileType);

            var fileContent = System.IO.File.ReadAllBytes(filePath);

            return(File(fileContent, fileType, fileName));
        }
Exemplo n.º 9
0
        public ActionResult GetFile([FromQuery] string fileName)
        {
            var rootPath = Directory.GetCurrentDirectory();

            var filePath = $"{rootPath}/PrivateFiles/{fileName}";

            var fileExists = System.IO.File.Exists(filePath);

            if (!fileExists)
            {
                return(NotFound());
            }
            // Sprawdzamy tutaj typ pliku (czy pdf, word, txt)
            var contentProvider = new FileExtensionContentTypeProvider();

            contentProvider.TryGetContentType(fileName, out string contentType);

            var fileContents = System.IO.File.ReadAllBytes(filePath);

            return(File(fileContents, contentType, fileName));
        }
Exemplo n.º 10
0
        public ActionResult Download(long bookId)
        {
            var bookRep = _unitOfWork.Repository <Book>();
            var bookObj = bookRep.GetById(bookId);
            //文件路径
            string path = Path.Combine(_configuration.GetSection("BookUploadFile").Value, bookObj.URL);

            if (string.IsNullOrWhiteSpace(bookObj.URL) || !System.IO.File.Exists(path))
            {
                return(RedirectToAction("Index", "Book"));
            }
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[Path.GetExtension(bookObj.URL)];
            var result   = File(new FileStream(path, FileMode.Open, FileAccess.Read), memi, bookObj.URL);

            //提交数据库
            bookObj.DownloadNum += 1;
            _unitOfWork.Commit();
            return(result);
        }
Exemplo n.º 11
0
        public IActionResult GetFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                path = "index.html";
            }
            var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", path);

            if (!System.IO.File.Exists(file))
            {
                return(NotFound());
            }
            var provider = new FileExtensionContentTypeProvider();

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

            return(PhysicalFile(file, contentType));
        }
Exemplo n.º 12
0
        public IActionResult Download(int?id)
        {
            string load = "";

            var model = _InspectionAttachmentService.getById(id.Value);

            load = "\\Files\\zbd\\";

            string sWebRootFolder = _hostingEnvironment.WebRootPath;
            var    fileProfile    = sWebRootFolder + load + model.AttachmentLoad;
            string sFileName      = model.AttachmentLoad;
            var    addrUrl        = sFileName;
            var    stream         = System.IO.File.OpenRead(fileProfile); //Path.GetExtension
            string fileExt        = Path.GetExtension(sFileName);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];

            // var downloadName = Path.GetFileName(addrUrl);
            return(File(stream, memi, model.Name));
        }
Exemplo n.º 13
0
        public IActionResult DownloadUpgradeBag(DTOUpgradeFileDownload dto)
        {
            string fileDirPath = Environment.CurrentDirectory + "/LocalFile/UpgradeBag/";

            string fileFullName;
            Repository <Prc_VersionInfo> repository = new Repository <Prc_VersionInfo>(DbContext);
            Prc_VersionInfo versionInfo             = repository.Get(a => a.ID == dto.VersionId);

            fileFullName = fileDirPath + versionInfo.UpgradeBagName;
            if (!System.IO.File.Exists(fileFullName))
            {
                throw new Exception("未找到文件");
            }

            var stream = System.IO.File.OpenRead(fileFullName);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[".zip"];

            return(File(stream, memi, Path.GetFileName(fileFullName)));
        }
Exemplo n.º 14
0
        public static async Task <Core.File> GetLocalFile(string path)
        {
            var fi = new FileInfo(path);
            var contentTypeProvider = new FileExtensionContentTypeProvider();

            Core.File file = null;
            if (fi != null)
            {
                using var stream = new MemoryStream();
                await fi.OpenRead().CopyToAsync(stream);

                contentTypeProvider.TryGetContentType($"{fi.Name}{fi.Extension}", out var contentType);
                file = new Core.File
                {
                    FileName    = fi.Name,
                    ContentType = contentType,
                    FileContent = stream.ToArray(),
                };
            }
            return(file);
        }
Exemplo n.º 15
0
        private CandidatoModel GenerarModel(int id)
        {
            var entity = this.candidatosClient.GetCandidatoAsync(id).Result;

            var model = new CandidatoModel(entity);

            foreach (var empleo in entity.Empleos)
            {
                var empleoModel = new EmpleoModel(empleo);

                model.Empleos.Add(empleoModel);
            }

            var path = entity.Can_PathCV;

            var memory = new MemoryStream();

            using (var stream = new FileStream(path, FileMode.Open))
            {
                stream.CopyTo(memory);
            }

            memory.Position = 0;

            var fileInfo = new FileInfo(path);

            var fileProvider = new FileExtensionContentTypeProvider();

            fileProvider.TryGetContentType(path, out string contentType);

            var file = new FormFile(memory, 0, memory.Length, null, Path.GetFileName(path))
            {
                Headers     = new HeaderDictionary(),
                ContentType = contentType
            };

            model.CV = file;

            return(model);
        }
Exemplo n.º 16
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");
                // 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
            //{
            //    ServeUnknownFileTypes = true,
            //    DefaultContentType = "application/javascript"
            //});

            var provider = new FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".vue"] = "application/javascript";

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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
Exemplo n.º 17
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(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            StaticFileOptions option = new StaticFileOptions();
            FileExtensionContentTypeProvider contentTypeProvider = (FileExtensionContentTypeProvider)option.ContentTypeProvider ??
                                                                   new FileExtensionContentTypeProvider();

            contentTypeProvider.Mappings.Add(".mem", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".data", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".memgz", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".datagz", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".unity3dgz", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".unityweb", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".jsgz", "application/x-javascript; charset=UTF-8");

            option.ContentTypeProvider = contentTypeProvider;

            app.UseStaticFiles(option);

            //app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 18
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();
            }

            //only serve .proto files
            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings.Clear();
            provider.Mappings[".proto"] = "text/plain";

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Protos")),
                RequestPath         = "/proto",
                ContentTypeProvider = provider
            });

            app.UseDirectoryBrowser(new DirectoryBrowserOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Protos")),
                RequestPath  = "/proto"
            });

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService <GreeterService>();

                endpoints.MapGet("/",
                                 async context =>
                {
                    await context.Response.WriteAsync(
                        "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });
        }
Exemplo n.º 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, YsbqcSetting set)
        {
            //var rewrite = new RewriteOptions().AddRedirect(@"m2/(\w+)", "?m3=$1");
            //app.UseRewriter(rewrite);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //MyRewrite(app);

            var provider = new FileExtensionContentTypeProvider();

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

            app.UseCookiePolicy();

            app.UseSession();

            app.UseMiddleware <SessionMiddleware>(set);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            GTXMethod.config = Configuration;
            GTXMethod.set    = ServiceProviderServiceExtensions.GetRequiredService <YsbqcSetting>(app.ApplicationServices);
        }
Exemplo n.º 20
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();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            var contentType = new FileExtensionContentTypeProvider();

            contentType.Mappings[".m3u8"] = "application/x-mpegURl";
            contentType.Mappings[".ts"]   = "video/MP2T";
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = contentType
            });

            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseSignalR(routes =>
            {
                routes.MapHub <ArticleHub>("/articleHub");
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 21
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");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            var provider = new FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".data"] = "application/unityweb";

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

            app.UseHttpsRedirection();
            //app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
Exemplo n.º 22
0
        //TODO pour plusieurs images
        public IActionResult GetImage(int id)
        {
            Produit requestedProduit = repoProduit.GetItem(id);

            if (requestedProduit != null)
            {
                string webRootpath = _environment.WebRootPath;
                string folderPath  = "\\images\\";

                string im = requestedProduit.Image.OrderByDescending(i => i.CheminAcces).Select(i => i.CheminAcces).SingleOrDefault();

                string fullPath = webRootpath + folderPath + im;

                if (System.IO.File.Exists(fullPath))
                {
                    FileStream fileOnDisk = new FileStream(fullPath, FileMode.Open);
                    byte[]     fileBytes;
                    using (BinaryReader br = new BinaryReader(fileOnDisk))
                    {
                        fileBytes = br.ReadBytes((int)fileOnDisk.Length);
                    }
                    //get content type
                    var    provider = new FileExtensionContentTypeProvider();
                    string contentType;
                    if (!provider.TryGetContentType(fullPath, out contentType))
                    {
                        contentType = "application/octet-stream";
                    }
                    return(File(fileBytes, contentType));
                }
                else
                {
                    return(NotFound());
                }
            }
            else
            {
                return(NotFound());
            }
        }
Exemplo n.º 23
0
        public IActionResult OnGetExportExcelEPPlus2(string Id)
        {
            this.Id = Id;
            var customer = _pinhuaContext.往来单位.FirstOrDefault(p => p.单位编号 == Id);

            StatementData = _pinhuaContext.myView_对账_汇总.Where(p => p.CustomerId == Id).OrderByDescending(p => p.OrderDate).ThenByDescending(p => p.OrderId).ThenBy(p => p.ItemId).ToList();
            using (ExcelPackage pck = new ExcelPackage(new FileInfo("epplus_template.xlsx"), new FileInfo("epplus_template.xlsx")))
            {
                //Create the worksheet
                string         sheetName = "Sheet1";
                ExcelWorksheet ws        = pck.Workbook.Worksheets[sheetName];
                ws.Cells.Style.Font.Name = "Microsoft YaHei";
                ws.Cells.Style.Font.Size = 10;
                //ws.InsertRow()
                //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                //ws.Cells["A1"].LoadFromCollection<DbQuery_对账汇总>(StatementData);
                ws.Cells[1, 1].Value = $"对帐单,{customer.单位名称} - {DateTime.Now.ToString("yyyyMMddHHmmss")}";
                var rowNum = 3;
                ws.InsertRow(rowNum + 1, StatementData.Count() - 1);
                foreach (var data in StatementData)
                {
                    ws.Cells[rowNum, 1].Value  = data.OrderDate.Value.ToString("yyyy-MM-dd");
                    ws.Cells[rowNum, 2].Value  = data.MovementTypeDescription;
                    ws.Cells[rowNum, 3].Value  = data.ItemId;
                    ws.Cells[rowNum, 4].Value  = data.Description;
                    ws.Cells[rowNum, 5].Value  = data.Specification;
                    ws.Cells[rowNum, 6].Value  = data.Qty;
                    ws.Cells[rowNum, 7].Value  = data.UnitQty;
                    ws.Cells[rowNum, 8].Value  = data.Unit;
                    ws.Cells[rowNum, 9].Value  = data.Price;
                    ws.Cells[rowNum, 10].Value = data.Amount;
                    rowNum++;
                }
                ws.Cells.AutoFitColumns();
                var saveAsFileName = $"对帐单,{customer.单位名称}-{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                var fileExt        = Path.GetExtension(saveAsFileName);
                var provider       = new FileExtensionContentTypeProvider();
                return(File(pck.GetAsByteArray(), provider.Mappings[fileExt], saveAsFileName));
            }
        }
Exemplo n.º 24
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //app.UseSerilogRequestLogging(options =>
            //{
            //    options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
            //    {
            //        diagnosticContext.Set("ResponseLength", httpContext.Response.ContentLength);
            //    };
            //});
            //GraphQL
            app.UseGraphQL <NorthwindSchema>();
            app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());

            // REST
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));

            app.UseHttpsRedirection();
            app.UseRouting();

            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings[".proto"] = "text/plain";
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Protos")),
                RequestPath         = "/protos",
                ContentTypeProvider = provider
            });

            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService <CustService>();
                endpoints.MapControllers();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 25
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();
            }

#if DEBUG
            Console.WriteLine("Skipping HttpsRedirection due to DEBUG run");
#else
            //Add Https Redirection only in release build
            app.UseHttpsRedirection();
#endif
            app.UseCors("AllowAnyOrigin");

            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings[".dat"]  = "application/octet-stream";
            provider.Mappings[".patt"] = "text/html";
            provider.Mappings[".mtl"]  = "text/html";
            provider.Mappings[".obj"]  = "text/html";

            app.UseStaticFiles(new StaticFileOptions
            {
                ServeUnknownFileTypes = true,
                FileProvider          = new PhysicalFileProvider(
                    Path.Combine(env.WebRootPath, "data")),
                RequestPath         = "/data",
                ContentTypeProvider = provider
            });

            app.UseDirectoryBrowser();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemplo n.º 26
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();

                var provider = new FileExtensionContentTypeProvider();

                // Add .scss mapping
                provider.Mappings[".scss"] = "text/css";
                app.UseStaticFiles(new StaticFileOptions()
                {
                    ContentTypeProvider = provider
                });
            }
            else
            {
                app.UseDeveloperExceptionPage();
                // 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.UseStaticFiles();
            }

            app.UseHttpsRedirection();
            app.UseSession();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 27
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            var mimeTypeProvider = new FileExtensionContentTypeProvider();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseResponseCompression();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 24;
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                        "public,max-age=" + durationInSeconds;

                    var headers     = ctx.Context.Response.Headers;
                    var contentType = headers["Content-Type"];

                    if (contentType != "application/x-gzip" && !ctx.File.Name.EndsWith(".gz"))
                    {
                        return;
                    }

                    var fileNameToTry = ctx.File.Name.Substring(0, ctx.File.Name.Length - 3);

                    if (!mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType))
                    {
                        return;
                    }
                    headers.Add("Content-Encoding", "gzip");
                    headers["Content-Type"] = mimeType;
                }
            });
Exemplo n.º 28
0
        private static void SetupStaticFiles(IApplicationBuilder app)
        {
            app.UseDefaultFiles();
            var configurationData = app.ApplicationServices.GetRequiredService <IOptions <ConfigurationData> >().Value;
            var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();

            fileExtensionContentTypeProvider.Mappings.Add(".db", "application/octet-stream");
            foreach (var directory in configurationData.ListingDictionary)
            {
                var fileServerOptions = new FileServerOptions
                {
                    FileProvider            = new PhysicalFileProvider(directory.Value),
                    RequestPath             = new PathString("/" + directory.Key),
                    EnableDirectoryBrowsing = true,
                    DirectoryBrowserOptions =
                    {
                        FileProvider = new PhysicalFileProvider(directory.Value),
                        RequestPath  = new PathString("/" + directory.Key),
                        Formatter    = new BootstrapFontAwesomeDirectoryFormatter(app.ApplicationServices
                                                                                  .GetRequiredService <IFileSystemHelper>())
                    },
                    StaticFileOptions = { ContentTypeProvider = fileExtensionContentTypeProvider },
                };
                app.UseFileServer(fileServerOptions);
            }
            // serve https certificate folder
            var wellKnownFolder = Path.Combine(Directory.GetCurrentDirectory(), @".well-known");

            if (Directory.Exists(wellKnownFolder))
            {
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider          = new PhysicalFileProvider(wellKnownFolder),
                    RequestPath           = new PathString("/.well-known"),
                    ServeUnknownFileTypes = true // serve extensionless file
                });
            }
            // wwwroot
            app.UseStaticFiles();
        }
Exemplo n.º 29
0
        /// <summary>
        /// 添加静态文件
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStaticFile(this IApplicationBuilder app)
        {
            var staticFileSettings = app.ApplicationServices.GetOptions <StaticFileSettingsOption>();;
            var path = AppDomain.CurrentDomain.BaseDirectory;

            if (staticFileSettings.StaticFileFolder?.Length > 0)
            {
                FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
                if (staticFileSettings.StaticFileMap != null)
                {
                    foreach (var map in staticFileSettings.StaticFileMap)
                    {
                        provider.Mappings[map.Suffix] = map.FileType;
                    }
                }
                foreach (var folder in staticFileSettings.StaticFileFolder)
                {
                    FileHelper.CreateDirectory(folder.Folder, path);
                    var requestPath = folder.RequestPath;

                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider          = new PhysicalFileProvider(Path.Combine(path, folder.Folder)),
                        ServeUnknownFileTypes = folder.ServeUnknownFileTypes,
                        ContentTypeProvider   = provider,
                        RequestPath           = requestPath,
                        DefaultContentType    = folder.DefaultContentType, // 设置未识别的MIME类型一个默认z值
                    });
                    if (staticFileSettings.UseDirectoryBrowser)
                    {
                        app.UseDirectoryBrowser(new DirectoryBrowserOptions()
                        {
                            FileProvider = new PhysicalFileProvider(Path.Combine(path, folder.Folder)), // 制定目录
                            RequestPath  = new PathString(requestPath)
                        });
                    }
                }
            }
            return(app);
        }
Exemplo n.º 30
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("/Home/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.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapHub <GameHub>("/GameHub");
            });

            FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();

            provider.Mappings[".glb"]  = "model/gltf+binary";
            provider.Mappings[".gltf"] = "model/gltf+json";

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
                RequestPath         = "/StaticFiles",
                ContentTypeProvider = provider
            });
        }
        public IActionResult Download(string keyValue)
        {
            string filepath = _waterMBriefApp.CopyModelFile();//Server.MapPath(_waterMBriefApp.CopyModelFile());// Server.MapPath(data.F_FilePath);
            string filename = FileHelper.GetFileName(filepath);

            if (!DateTime.TryParse(keyValue, out var currentDate))
            {
                currentDate = DateTime.Today;
            }
            var startDate = currentDate.Date.AddDays(1 - currentDate.Day);
            var endDate   = startDate.AddMonths(1);

            _waterMBriefApp.FillData(startDate, endDate, filepath, filename);

            var fileExt = FileHelper.GetExtension(filepath);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi     = provider.Mappings[fileExt];
            var data     = FileHelper.GetFileData(filepath);

            return(File(data, memi, FileHelper.GetFileName(filepath)));
        }
        public async Task <ActionResult> DownloadFile(int id)
        {
            // validation and get the file

            var filePath = $"{id}.txt";

            if (!System.IO.File.Exists(filePath))
            {
                await System.IO.File.WriteAllTextAsync(filePath, "Hello World!");
            }

            var provider = new FileExtensionContentTypeProvider();

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

            var bytes = await System.IO.File.ReadAllBytesAsync(filePath);

            return(File(bytes, contentType, Path.GetFileName(filePath)));
        }
Exemplo n.º 33
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // Set up custom content type for GLTF (GLB) files
            var contentTypeProvider = new FileExtensionContentTypeProvider();

            contentTypeProvider.Mappings[".gltf"] = "model/gltf+json";
            // Configure request pipeline
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseBallastServer();
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions {
                ContentTypeProvider = contentTypeProvider
            });
        }
Exemplo n.º 34
0
		private void FileSystemWatcherOnCreatedAsync(object sender, FileSystemEventArgs fileSystemEventArgs)
		{
			FileSystemWatcherEx fileSystemWatcherEx;
			bool continueRetry;
			IIntegrationMessage integrationMessage;
			DateTime messageReceivedUtc = DateTime.UtcNow;
			string filePath, fileName, contentType;
			Stream stream;
			IContentTypeProvider contentTypeProvider;

			this.WriteLogSynchronized("INBOUND: File system event processed via thread pool thread '{0}'.", Thread.CurrentThread.ManagedThreadId);
			fileSystemWatcherEx = (FileSystemWatcherEx)sender;

			filePath = Path.GetFullPath(fileSystemEventArgs.FullPath);
			fileName = Path.GetFileName(filePath);

			// ignore new directories
			if (Directory.Exists(filePath))
				return;

			integrationMessage = this.IntegrationFactory.CreateMessage();

			this.WriteLogSynchronized("INBOUND: Integration message ID '{0}' created on thread pool thread '{1}'.", integrationMessage.RunTimeId, Thread.CurrentThread.ManagedThreadId);

			integrationMessage.Metadata.Add(AdapterMetadataConstants.INBOUND_ORIGINAL_FILE_PATH, fileSystemEventArgs.FullPath);
			integrationMessage.Metadata.Add(AdapterMetadataConstants.INBOUND_ORIGINAL_FILE_NAME, fileSystemEventArgs.Name);
			integrationMessage.Metadata.Add(AdapterMetadataConstants.INBOUND_ORIGINAL_DIRECTORY_PATH, Path.GetDirectoryName(fileSystemEventArgs.FullPath));

			continueRetry = true;

			while (!FileReady(filePath))
			{
				if (!(continueRetry = TryRetryUntil(messageReceivedUtc)))
					break; //throw new InvalidOperationException(string.Format("{0}", fileSystemEventArgs.FullPath));
			}

			if (!continueRetry)
				return; // give up

			// stream is not owned here, deleted on close...???
			stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, FileOptions.SequentialScan | FileOptions.DeleteOnClose);

			contentTypeProvider = new FileExtensionContentTypeProvider();

			integrationMessage.DataStream = stream;
			contentTypeProvider.TryGetContentType(filePath, out contentType);
			integrationMessage.ContentType = contentType;
			integrationMessage.ContentEncoding = null; // deferred until stream to dropbox

			this.PostInboundMessage(fileSystemWatcherEx.Endpoint, integrationMessage);
		}
Exemplo n.º 35
-1
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseDefaultFiles();
            var contentTypeProvider = new FileExtensionContentTypeProvider();
            contentTypeProvider.Mappings[".nzd"] = "application/octet-stream";
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = contentTypeProvider
            });

            // At some stage we may want an MVC view for the home page, but at the moment
            // we're just serving static files, so we don't need much.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
        }