Example #1
0
        public void Configure(IApplicationBuilder app)
        {
            var options = new StaticFileOptions();

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
Example #2
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);
        }
        /// <summary>
        /// Creates a new instance of the StaticFileMiddleware.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline.</param>
        /// <param name="options">The configuration options.</param>
        /// <param name="loggerFactory">An <see cref="ILoggerFactory"/> instance used to create loggers.</param>
        public StaticFileMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, StaticFileOptions options, ILoggerFactory loggerFactory)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (hostingEnv == null)
            {
                throw new ArgumentNullException(nameof(hostingEnv));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            if (options.ContentTypeProvider == null)
            {
                throw new ArgumentException(Resources.Args_NoContentTypeProvider);
            }
            options.ResolveFileProvider(hostingEnv);

            _next = next;
            _options = options;
            _matchUrl = options.RequestPath;
            _logger = loggerFactory.CreateLogger<StaticFileMiddleware>();
        }
        public StaticFileContext(HttpContext context, StaticFileOptions options, PathString matchUrl)
        {
            _context = context;
            _options = options;
            _matchUrl = matchUrl;
            _request = context.Request;
            _response = context.Response;

            _method = null;
            _isGet = false;
            _isHead = false;
            _subPath = PathString.Empty;
            _contentType = null;
            _fileInfo = null;
            _length = 0;
            _lastModified = new DateTime();
            _etag = null;
            _etagQuoted = null;
            _lastModifiedString = null;
            _ifMatchState = PreconditionState.Unspecified;
            _ifNoneMatchState = PreconditionState.Unspecified;
            _ifModifiedSinceState = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;
            _ranges = null;
        }
 /// <summary>
 /// Enables static file serving with the given options
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static IAppBuilder UseStaticFiles(this IAppBuilder builder, StaticFileOptions options)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     return builder.Use<StaticFileMiddleware>(options);
 }
 /// <summary>
 /// Enables static file serving with the given options
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static IBuilder UseStaticFiles(this IBuilder builder, StaticFileOptions options)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     return builder.Use(next => new StaticFileMiddleware(next, options).Invoke);
 }
Example #7
0
 private void UsarServidorDeArquivos()
 {
     app.UseFileServer();
     var options = new StaticFileOptions
     {
         ContentTypeProvider = new JsonContentTypeProvider()
     };
     app.UseStaticFiles(options);
 }
Example #8
0
        public static IAppBuilder UseStaticFiles(this IAppBuilder builder, Action<StaticFileOptions> configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            var options = new StaticFileOptions();
            configuration(options);
            return UseStaticFiles(builder, options);
        }
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, IHostingEnvironment env)
        {
            var path = Path.Combine(env.ContentRootPath, "node_modules");
            var provider = new PhysicalFileProvider(path);

            var options = new StaticFileOptions();
            options.RequestPath = "/node_modules";
            options.FileProvider = provider;
            app.UseStaticFiles(options);
            return app;
        }
Example #10
0
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.MinimumLevel = LogLevel.Information;
            loggerFactory.AddConsole();

            // Add Application Insights to the request pipeline to track HTTP request telemetry data.
            app.UseApplicationInsightsRequestTelemetry();

            // Configure the HTTP request pipeline.

            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                var options = new StaticFileOptions
                {
                    ContentTypeProvider = new FileExtensionContentTypeProvider()
                };
                ((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
                    new KeyValuePair<string, string>(".less", "text/css"));
                app.UseStaticFiles(options);
                app.UseErrorPage();
            }
            else
            {
                app.Use(next => async context =>
                {
                    if(context.Request.Host.Value.StartsWith("www.") || !context.Request.IsHttps) {
                        context.Response.Redirect(string.Format("https://coynapp.com{0}", context.Request.Path.Value), true);
                        return;
                    }
                    // incoming code goes here
                    await next(context);
                    // outgoing code goes here
                });
                // Add Error handling middleware which catches all application specific errors and
                // send the request to the following path or controller action.
                app.UseErrorHandler("/Home/Error");
                app.UseStaticFiles();
            }

            // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
            app.UseApplicationInsightsExceptionTelemetry();

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

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            });
        }
Example #11
0
        private static void UseLaterListStaticFiles(IApplicationBuilder app, IHostEnvironment env)
        {
            var webRootPath  = env.GetWebRootPath();
            var fileProvider = webRootPath != null
                ? (IFileProvider) new PhysicalFileProvider(webRootPath)
                : new NullFileProvider();

            var staticFileOptions = new StaticFileOptions {
                FileProvider = fileProvider
            };

            app.UseStaticFiles(staticFileOptions);
        }
Example #12
0
        private StaticFileMiddleware CreateStaticFileMiddleware(
            RequestDelegate next,
            IWebHostEnvironment hostingEnv,
            ILoggerFactory loggerFactory)
        {
            var staticFileOptions = new StaticFileOptions
            {
                RequestPath  = $"/{_options.RoutePrefix}",
                FileProvider = new EmbeddedFileProvider(typeof(SerilogUiMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
            };

            return(new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory));
        }
Example #13
0
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, string root)
        {
            var path     = Path.Combine(root, "node_modules");
            var provider = new PhysicalFileProvider(path);

            var option = new StaticFileOptions();

            option.RequestPath  = "/node_modules";                                      //Sana bu adresden bir request gelirse onu yukarıda verdiğim roota yönlendir.
            option.FileProvider = provider;

            app.UseStaticFiles(option);
            return(app);
        }
Example #14
0
        // This is extension method for IApplicationBuilder, so use this keyword
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <param name="root">root of this project</param>
        /// <returns></returns>
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, string root)
        {
            // a path to the node_modules folder
            var path         = Path.Combine(root, "node_modules");
            var fileProvider = new PhysicalFileProvider(path);
            var options      = new StaticFileOptions
            {
                RequestPath = "/node_modules", FileProvider = fileProvider
            };

            app.UseStaticFiles(options);
            return(app);
        }
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder applicationBuilder, string root)
        {
            var path         = Path.Combine(root, "node_modules");
            var fileProvider = new PhysicalFileProvider(path);

            var options = new StaticFileOptions();

            options.RequestPath  = "/node_modules";
            options.FileProvider = fileProvider;

            applicationBuilder.UseStaticFiles(options);
            return(applicationBuilder);
        }
        private StaticFileMiddleware CreateStaticFileMiddleware(
            RequestDelegate next,
            IHostingEnvironment hostingEnv,
            ILoggerFactory loggerFactory,
            MicrophobiaDashboardOptions options)
        {
            var staticFileOptions = new StaticFileOptions
            {
                FileProvider = new EmbeddedFileProvider(typeof(DashboardMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
            };

            return(new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory));
        }
Example #17
0
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, IApplicationEnvironment env)
        {
            var path     = Path.Combine(env.ApplicationBasePath, "node_modules");
            var provider = new PhysicalFileProvider(path);

            var options = new StaticFileOptions();

            options.RequestPath  = "/node_modules";
            options.FileProvider = provider;

            app.UseStaticFiles(options);
            return(app);
        }
Example #18
0
        public static IApplicationBuilder CustomStaticFiles(this IApplicationBuilder app)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "node_modules");

            var options = new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(path),
                RequestPath  = "/modules"
            };

            app.UseStaticFiles(options);
            return(app);
        }
        /// <summary>
        /// Enables static file serving with the given options
        /// </summary>
        /// <param name="app"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<StaticFileMiddleware>(options);
        }
Example #20
0
        public void ServeUnknownFileTypesConfiguration(IAppBuilder app)
        {
            var staticFileOptions = new StaticFileOptions();

            app.Use((context, next) =>
            {
                staticFileOptions.ServeUnknownFileTypes = context.Request.Headers.ContainsKey("ServeUnknown") ? true : false;
                staticFileOptions.DefaultContentType    = staticFileOptions.ServeUnknownFileTypes ? "unknown/unknown" : null;
                return(next.Invoke());
            });

            app.UseStaticFiles(staticFileOptions);
        }
Example #21
0
        public void PostConfigure(string name, StaticFileOptions options)
        {
            options = options ?? throw new ArgumentNullException(nameof(options));

            options.ContentTypeProvider ??= new FileExtensionContentTypeProvider();
            if (options.FileProvider == null && _environment.WebRootFileProvider == null)
            {
                throw new InvalidOperationException(Resources.FileProviderNotFound);
            }

            options.FileProvider ??= _environment.WebRootFileProvider;
            options.FileProvider = new CompositeFileProvider(options.FileProvider, new EmbeddedFileProvider(typeof(TAssemblyType).Assembly));
        }
Example #22
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime appLife)
        {
            // Sign up to application shutdown so we can do proper cleanup
            appLife.ApplicationStopping.Register(onApplicationStopping);
            // Static file options: inject caching info for all static files.
            StaticFileOptions sfo = new StaticFileOptions
            {
                OnPrepareResponse = (context) =>
                {
                    // Genuine static staff: tell browser to cache indefinitely
                    bool toCache = context.Context.Request.Path.Value.StartsWith("/static/");
                    toCache |= context.Context.Request.Path.Value.StartsWith("/prod-");
                    if (toCache)
                    {
                        context.Context.Response.Headers["Cache-Control"] = "private, max-age=31536000";
                        context.Context.Response.Headers["Expires"]       = DateTime.UtcNow.AddYears(1).ToString("R");
                    }
                    // For everything coming from "/files/**", disable caching
                    else if (context.Context.Request.Path.Value.StartsWith("/files/"))
                    {
                        context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
                        context.Context.Response.Headers["Pragma"]        = "no-cache";
                        context.Context.Response.Headers["Expires"]       = "0";
                    }
                    // The rest of the content is served by IndexController, which adds its own cache directive.
                }
            };

            // Static files (JS, CSS etc.) served directly.
            app.UseStaticFiles(sfo);
            // Authentication for MVC calls
            app.Use(async(context, next) =>
            {
                var auth = app.ApplicationServices.GetService <Auth>();
                int userId; string userName;
                auth.CheckSession(context.Request.Headers, out userId, out userName);
                if (userId != -1)
                {
                    context.Response.Headers.Add("ZydeoLoggedIn", "true");
                }
                ;
                await next.Invoke();
            });
            // Serve our (single) .cshtml file, and serve API requests.
            app.UseMvc(routes =>
            {
                routes.MapRoute("api", "api/{controller}/{action}/{*paras}", new { paras = "" });
                routes.MapRoute("files", "files/{name}", new { controller = "Files", action = "Get" });
                routes.MapRoute("default", "{*paras}", new { controller = "Index", action = "Index", paras = "" });
            });
        }
Example #23
0
        public IWebHost Build()
        {
            return(WebHost.CreateDefaultBuilder().
                   ConfigureServices(services =>
            {
                services.AddTransient(_ => this);
                services.AddTransient(_ => this.repo);
                services.AddSignalR().AddJsonProtocol(o =>
                                                      o.PayloadSerializerSettings.Converters.Add(new StringEnumConverter()));
                services.AddSignalR();
                services.AddMvc();
            }).
                   Configure(app =>
            {
                var env = app.ApplicationServices.GetService <IHostingEnvironment>();

                app.UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider = new PhysicalFileProvider(this.repo.Path),
                    RequestPath = "/img"
                });

                app.UseSignalR(config => config.MapHub <MemeHub>("/MemeHub"));

                app.UseMvc();

                StaticFileOptions fileOptions = new StaticFileOptions()
                {
                    FileProvider = new EmbeddedFileProvider(Assembly.GetExecutingAssembly(), "MemeBoard.Web.client")
                };

                app.UseSpa(spa =>
                {
                    if (env.IsDevelopment())
                    {
                        spa.ApplicationBuilder.UseDeveloperExceptionPage();
                        spa.UseProxyToSpaDevelopmentServer("http://127.0.0.1:5500");
                    }

                    spa.Options.DefaultPageStaticFileOptions = fileOptions;
                });
                app.UseSpaStaticFiles(fileOptions);
            }).
#if DEBUG
                   UseEnvironment("development").
#else
                   UseEnvironment("production").
#endif
                   UseUrls($"http://*:5001/").
                   Build());
        }
Example #24
0
        //Node package larımız Core da wwwroot altında toplanmadığı için nereden bağlanacağını burada belirtiyoruz.
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, string root)
        {
            var path     = Path.Combine(root, "node_modules"); //node_modules klasörünü root stringine bağladık.
            var provider = new PhysicalFileProvider(path);

            var option = new StaticFileOptions();

            option.RequestPath  = "/node_modules";
            option.FileProvider = provider;

            app.UseStaticFiles(option);

            return(app);
        }
Example #25
0
        public void DiscoveryOption()
        {
            var mock         = new Mock <IWebHostEnvironment>();
            var fileProvider = new EmbeddedFileProvider(typeof(RestOfPagesTests).Assembly);

            mock.Setup(m => m.ContentRootFileProvider).Returns(fileProvider);
            var microwaveUiConfigureOptions = new MicrowaveUiConfigureOptions(mock.Object);

            var staticFileOptions = new StaticFileOptions();

            microwaveUiConfigureOptions.PostConfigure("hm", staticFileOptions);

            Assert.AreEqual(typeof(CompositeFileProvider), staticFileOptions.FileProvider.GetType());
        }
Example #26
0
 public UrlImageResizerProvider(IOptions <UrlImageResizerOptions> options,
                                IOptions <StaticFileOptions> staticFileOptions,
                                ILogger <UrlImageResizerProvider> logger,
                                IImageProcessor imageResizer,
                                IWebHostEnvironment hostingEnv)
 {
     this.options       = options;
     _staticFileOptions = staticFileOptions.Value;
     _logger            = logger;
     _fileProvider      = _staticFileOptions.FileProvider ?? Helpers.ResolveFileProvider(hostingEnv);
     _imageResizer      = imageResizer;
     pathLocks          = new ConcurrentDictionary <string, object>();
     _cachePath         = Path.Combine(hostingEnv.WebRootPath, options.Value.CachePath);
 }
Example #27
0
        //miidlewares olması için ilk paramtre this sonrada IApplicationBuilder genişletcez
        //startup.cs öyle çünkü
        public static IApplicationBuilder CustomStaticFiles(this IApplicationBuilder app)
        {
            //dışarıya açacağımız modul = node_modules
            var path = Path.Combine(Directory.GetCurrentDirectory(), "node_modules");

            var options = new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(path),
                RequestPath  = "/modules" // takma ismi node_modules bununlar erişcez
            };

            app.UseStaticFiles(options);
            return(app);
        }
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, string root)
        {
            //Tamamı Root Altında Olmayan node_modules'a root altında göstermek için yapıldı.
            var path     = Path.Combine(root, "node_modules"); //Root altındaki node_modules arayacak ve Combine edecek(Root ile node_modules)
            var provider = new PhysicalFileProvider(path);     //static dosyaları taşımak adına servis nesnesi

            var options = new StaticFileOptions();

            options.RequestPath  = "/node_modules";
            options.FileProvider = provider;

            app.UseStaticFiles(options);
            return(app);
        }
Example #29
0
        private StaticFileMiddleware CreateStaticFileMiddleware(
            RequestDelegate next,
            IHostingEnvironment hostingEnv,
            ILoggerFactory loggerFactory,
            ReDocOptions options)
        {
            var staticFileOptions = new StaticFileOptions
            {
                RequestPath  = string.IsNullOrEmpty(options.RoutePrefix) ? string.Empty : $"/{options.RoutePrefix}",
                FileProvider = new EmbeddedFileProvider(typeof(ReDocMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
            };

            return(new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory));
        }
Example #30
0
    public static IApplicationBuilder UseStaticResources(this IApplicationBuilder app, HostingEnvironment env)
    {
        var path     = Path.Combine(env.ContentRootPath, "dist"); // this allows for serving up contents in a folder named 'static'
        var provider = new PhysicalFileProvider(path);

        var options = new StaticFileOptions();

        options.RequestPath = ""; // an empty string will give the *appearance* of it being served up from the root
        //options.RequestPath = "/content"; // this will use the URL path named content, but could be any made-up name you want
        options.FileProvider = provider;

        app.UseStaticFiles(options);
        return(app);
    }
Example #31
0
 public void Configure(IApplicationBuilder app)
 {
     app.UseIISPlatformHandler();
     app.UseMvc(builder =>
      {
          builder.MapRoute(name: "defaultApi", template: "api/{controller}/{action}");
      });
     app.UseDefaultFiles();
     var options = new StaticFileOptions();
     var provider = new FileExtensionContentTypeProvider();
     provider.Mappings.Add(".iso", "application/octet-stream");
     options.ContentTypeProvider = provider;
     app.UseStaticFiles(options);
 }
        public async Task Should_use_the_file_provider_of_StaticFileOptions_if_it_is_provided()
        {
            // Arrange
            var fileInfo = Substitute.For <IFileInfo>();

            fileInfo.Exists.Returns(true);
            fileInfo.IsDirectory.Returns(false);
            fileInfo.Length.Returns(12);
            fileInfo.LastModified.Returns(new DateTimeOffset(2018, 12, 16, 13, 36, 0, new TimeSpan()));
            fileInfo.CreateReadStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes("fileprovider")));

            var mockFileProvider = Substitute.For <IFileProvider>();

            mockFileProvider.GetFileInfo("/i_only_exist_in_mociFileProvider.html").Returns(fileInfo);

            var staticFileOptions = new StaticFileOptions()
            {
                FileProvider = mockFileProvider
            };

            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.UseCompressedStaticFiles(staticFileOptions);
                app.Use(next =>
                {
                    return(async context =>
                    {
                        // this test should never call the next middleware
                        // set status code to 999 to detect a test failure
                        context.Response.StatusCode = 999;
                    });
                });
            }).UseWebRoot(Path.Combine(Environment.CurrentDirectory, "wwwroot"));
            var server = new TestServer(builder);

            // Act
            var client = server.CreateClient();

            client.DefaultRequestHeaders.Add("Accept-Encoding", "br");
            var response = await client.GetAsync("/i_only_exist_in_mociFileProvider.html");

            var content = await response.Content.ReadAsStringAsync();

            // Assert
            response.StatusCode.Should().Be(200);
            content.Should().Be("fileprovider");
            response.Content.Headers.TryGetValues("Content-Type", out IEnumerable <string> contentTypeValues);
            contentTypeValues.Single().Should().Be("text/html");
        }
        // 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.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c => {
                //c.SwaggerEndpoint("v1/swagger.json", "My API V1");
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
            });

            StaticFileOptions options = new StaticFileOptions();
            FileExtensionContentTypeProvider typeProvider = new FileExtensionContentTypeProvider();

            if (!typeProvider.Mappings.ContainsKey(".woff2"))
            {
                typeProvider.Mappings.Add(".woff2", "application/font-woff2");
            }
            if (!typeProvider.Mappings.ContainsKey(".woff"))
            {
                typeProvider.Mappings.Add(".woff", "application/font-woff");
            }
            if (!typeProvider.Mappings.ContainsKey(".ttf"))
            {
                typeProvider.Mappings.Add(".ttf", "application/font-ttf");
            }
            options.ContentTypeProvider = typeProvider;
            app.UseStaticFiles();
            app.UseHttpsRedirection();
            app.UseFileServer();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
        }
        public void LookupFileInfo_ReturnsFalse_IfFileDoesNotExist()
        {
            // Arrange
            var options = new StaticFileOptions();
            var context = new StaticFileContext(new DefaultHttpContext(), options, PathString.Empty, NullLogger.Instance, new TestFileProvider(), new FileExtensionContentTypeProvider());

            // Act
            var validateResult = context.ValidatePath();
            var lookupResult   = context.LookupFileInfo();

            // Assert
            Assert.True(validateResult);
            Assert.False(lookupResult);
        }
Example #35
0
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="next">A function that can process an HTTP request</param>
        /// <param name="hostingEnv">运行环境</param>
        /// <param name="loggerFactory">logger</param>
        public JcApiHelperUIMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, ILoggerFactory loggerFactory)
        {
            apiHelperAssembly = typeof(JcApiHelperUIMiddleware).GetTypeInfo().Assembly;
            apiResources      = apiHelperAssembly.GetManifestResourceNames().ToList();

            StaticFileOptions staticFileOptions = new StaticFileOptions
            {
                RequestPath  = "/ApiHelper",
                FileProvider = new EmbeddedFileProvider(apiHelperAssembly, embeddedFileNamespace)
            };

            staticFileMiddleware = new StaticFileMiddleware(next, hostingEnv,
                                                            Options.Create(staticFileOptions), loggerFactory);
        }
Example #36
0
        /// <summary>
        /// Creates a new instance of the JsxFileMiddleware.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline.</param>
        /// <param name="options">The configuration options.</param>
        public JsxFileMiddleware(Func <IDictionary <string, object>, Task> next, JsxFileOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }

            _next = next;

            // Default values
            options      = options ?? new JsxFileOptions();
            _extensions  = (options.Extensions == null || !options.Extensions.Any()) ? new[] { ".jsx", ".js" } : options.Extensions;
            _fileOptions = options.StaticFileOptions ?? new StaticFileOptions();
        }
        public static void Enable(IApplicationBuilder ApplicationBuilder, ClientPackagesOptions Options)
        {
            string requestUrlPath = Options.RequestUrlPath.StartsWith("/")
                ? Options.RequestUrlPath
                : $"/{Options.RequestUrlPath}";
            PhysicalFileProvider fileProvider      = new PhysicalFileProvider(Options.FilePath);
            StaticFileOptions    staticFileOptions = new StaticFileOptions
            {
                RequestPath  = requestUrlPath,
                FileProvider = fileProvider
            };

            ApplicationBuilder.UseStaticFiles(staticFileOptions);
        }
Example #38
0
        void ConfigFileSystem(IAppBuilder app)
        {
            string AppRootPath = Path.Combine(Environment.CurrentDirectory, @"..\..");
            var    fileOptions = new StaticFileOptions
            {
                FileSystem = new PhysicalFileSystem(AppRootPath),
            };

            app.UseStaticFiles(fileOptions);

            ScriptsRootPath  = Path.Combine(AppRootPath, "scripts");
            HtmlRootPath     = Path.Combine(AppRootPath, "View");
            ResourceRootPath = Path.Combine(AppRootPath, "res");
        }
Example #39
0
		/// <summary>
		/// Global user code
		/// </summary>
		/// <summary>
		/// Static constructor
		/// </summary>

		static project1()
		{
			var provider = new FileExtensionContentTypeProvider();
			FileOptions = new StaticFileOptions()
			{
				ContentTypeProvider = provider
			};

			// ContentType Mapping event
			ContentType_Mapping(provider.Mappings);

			// Class Init event
			Class_Init();
		}
        /// <summary>Invoked to configure a TOptions instance.</summary>
        /// <param name="name">The name of the options instance being configured.</param>
        /// <param name="options">The options instance to configured.</param>
        public void PostConfigure(string name, StaticFileOptions options)
        {
            name    = name ?? throw new ArgumentNullException(nameof(name));
            options = options ?? throw new ArgumentNullException(nameof(options));

            options.ContentTypeProvider = options.ContentTypeProvider ?? new FileExtensionContentTypeProvider();
            if (options.FileProvider == null && Environment.WebRootFileProvider == null)
            {
                throw new InvalidOperationException("Missing FileProvider.");
            }

            options.FileProvider = options.FileProvider ?? Environment.WebRootFileProvider;
            options.FileProvider = new CompositeFileProvider(options.FileProvider, new EmbeddedFileProvider());
        }
Example #41
0
        public static void Main()
        {
            var options = new StaticFileOptions
            {
                ServeUnknownFileTypes = true,
                DefaultContentType    = "image/jpg"
            };

            Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder.Configure(
                                          app => app.UseStaticFiles(options)))
            .Build()
            .Run();
        }
Example #42
0
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, string root)
        {
            var path     = Path.Combine(root, "node_modules"); //rootla nodemodulesi combine et yani birleştir dedik yani root/nodemodules yazıcak.
            var provider = new PhysicalFileProvider(path);     //provider static dosyaları taşımak için ara servis nesnesi.

            var options = new StaticFileOptions();

            options.RequestPath  = "/node_modules"; //sana bir istek gelirse
            options.FileProvider = provider;

            app.UseStaticFiles(options);

            return(app);
        }
Example #43
0
        public StaticFileMiddleware(AppFunc next, StaticFileOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _next = next;
            _options = options;
            _matchUrl = options.RequestPath + "/";
        }
        public void LookupFileInfo_ReturnsFalse_IfFileDoesNotExist()
        {
            // Arrange
            var options = new StaticFileOptions();
            options.FileProvider = new TestFileProvider();
            var context = new StaticFileContext(new DefaultHttpContext(), options, PathString.Empty, NullLogger.Instance);

            // Act
            var validateResult = context.ValidatePath();
            var lookupResult = context.LookupFileInfo();

            // Assert
            Assert.True(validateResult);
            Assert.False(lookupResult);
        }
        /// <summary>
        /// Enables static file serving with the given options
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configureOptions"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, Action<StaticFileOptions> configureOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (configureOptions == null)
            {
                throw new ArgumentNullException(nameof(configureOptions));
            }

            var options = new StaticFileOptions();
            configureOptions(options);

            return app.UseMiddleware<StaticFileMiddleware>(options);
        }
        protected StaticFileOptions GetOptions(ServerOptions serverOptions)
        {
            var options = new StaticFileOptions();
            if (serverOptions == null)
            {
                return options;
            }

            var provider = (FileExtensionContentTypeProvider)options.ContentTypeProvider;

            foreach (var option in serverOptions.MimeTypes)
            {
                provider.Mappings.Add(option.Key, option.Value);
            }

            return options;
        }
        private static HttpClient CreateHttpClient(int maxKiloBytesPerSecond = -1)
        {
            var staticFileOptions = new StaticFileOptions
            {
                FileSystem = new EmbeddedResourceFileSystem(
                    typeof(MaxBandwidthPerRequestTests).Assembly,
                    "LimitsMiddleware.Files")
            };
            var appFunc = new AppBuilder()
                .MaxBandwidthPerRequest(maxKiloBytesPerSecond)
                .UseStaticFiles(staticFileOptions)
                .Build();

            return new HttpClient(new OwinHttpMessageHandler(appFunc))
            {
                BaseAddress = new Uri("http://localhost")
            };
        }
Example #48
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
            app.UseWebApi(ConfigureWebApi());

            var staticFileOptions = new StaticFileOptions
            {
                RequestPath = new PathString("/web"),
                FileSystem = new PhysicalFileSystem(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "webdir"))
            };
            app.UseDefaultFiles(new DefaultFilesOptions
            {
                RequestPath = staticFileOptions.RequestPath,
                FileSystem = staticFileOptions.FileSystem,
            });
            app.UseStaticFiles(staticFileOptions);
        }
        public void Configuration(IAppBuilder app)
        {
            var dir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "webdir");

              var staticFilesOptions = new StaticFileOptions
              {
            RequestPath = new PathString(""),
            FileSystem = new PhysicalFileSystem(dir)
              };
              app.UseStaticFiles(staticFilesOptions);

              var config = new HttpConfiguration();
              config.Formatters.Clear();
              config.Formatters.Add(new JsonMediaTypeFormatter());
              config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
              {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
              };
              config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
              config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
              app.UseWebApi(config);
        }
        public void LookupFileInfo_ReturnsTrue_IfFileExists()
        {
            // Arrange
            var options = new StaticFileOptions();
            var fileProvider = new TestFileProvider();
            fileProvider.AddFile("/foo.txt", new TestFileInfo
            {
                LastModified = new DateTimeOffset(2014, 1, 2, 3, 4, 5, TimeSpan.Zero)
            });
            options.FileProvider = fileProvider;
            var pathString = new PathString("/test");
            var httpContext = new DefaultHttpContext();
            httpContext.Request.Path = new PathString("/test/foo.txt");
            var context = new StaticFileContext(httpContext, options, pathString, NullLogger.Instance);

            // Act
            context.ValidatePath();
            var result = context.LookupFileInfo();

            // Assert
            Assert.True(result);
        }
        /// <summary>
        /// Creates a new instance of the StaticFileMiddleware.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline.</param>
        /// <param name="options">The configuration options.</param>
        public StaticFileMiddleware(RequestDelegate next, StaticFileOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (options.ContentTypeProvider == null)
            {
                throw new ArgumentException(Resources.Args_NoContentTypeProvider);
            }
            if (options.FileSystem == null)
            {
                options.FileSystem = new PhysicalFileSystem("." + options.RequestPath.Value);
            }

            _next = next;
            _options = options;
            _matchUrl = options.RequestPath;
        }
Example #52
0
        public StaticFileContext(IDictionary<string, object> environment, StaticFileOptions options, string matchUrl)
        {
            _environment = environment;
            _options = options;
            _matchUrl = matchUrl;
            _request = new OwinRequest(environment);
            _response = new OwinResponse(environment);

            _method = null;
            _isGet = false;
            _isHead = false;
            _subPath = null;
            _contentType = null;
            _fileInfo = null;
            _length = 0;
            _lastModified = new DateTime();
            _etag = null;
            _lastModifiedString = null;
            _ifMatchState = PreconditionState.Unspecified;
            _ifNoneMatchState = PreconditionState.Unspecified;
            _ifModifiedSinceState = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;
        }
Example #53
0
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.MinimumLevel = LogLevel.Information;
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            loggerFactory.AddEventLog();
            var logger = loggerFactory.CreateLogger("ToprakWeb");

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseErrorPage();
            }

            app.UseApplicationInsightsRequestTelemetry();
            app.UseErrorHandler(
                errorApp =>
                    {
                        var telemetryClient = new TelemetryClient();
                        errorApp.Run(
                            async context =>
                                {
                                    context.Response.StatusCode = 200;
                                    context.Response.ContentType = "text/html";
                                    await context.Response.WriteAsync("<html><body>\r\n");
                                    await
                                        context.Response.WriteAsync(
                                            "Beklenmiyen bir hata olustu.<br>\r\n");

                                    var error = context.GetFeature<IErrorHandlerFeature>();
                                    if (error != null)
                                    {
                                        // This error would not normally be exposed to the client
                                        logger.LogCritical($"{error.Error.Message} \n {error.Error.StackTrace}");
                                    }
                                    await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n");
                                    await context.Response.WriteAsync("</body></html>\r\n");
                                    await context.Response.WriteAsync(new string(' ', 512)); // Padding for IE
                                });
                    });
            app.UseApplicationInsightsExceptionTelemetry();

            var adminEmails = this.config["adminEmails"];
            var facebookAppId = this.config["FacebookAppId"];
            if (string.IsNullOrEmpty(facebookAppId) && env.IsDevelopment())
            {
                facebookAppId = this.config["AppSettings:FacebookAppId"];
            }
            var facebookAppSecret = this.config["FacebookAppSecret"];
            if (string.IsNullOrEmpty(facebookAppSecret) && env.IsDevelopment())
            {
                facebookAppSecret = this.config["AppSettings:FacebookAppSecret"];
            }
            app.UseToprakWebAuthentication(
                "ToprakWeb",
                (options) =>
                {
                    options.FacebookAppId = facebookAppId;
                        options.FacebookAppSecret = facebookAppSecret;
                        options.GoogleClientId = this.config["AppSettings:GoogleClientId"];
                        options.GoogleClientSecret = this.config["AppSettings:GoogleClientSecret"];
                        options.AdminIds = adminEmails.Split(',');
                    });
            app.UseDefaultFiles();

            var staticFileOptions = new StaticFileOptions();
            var typeProvider = new FileExtensionContentTypeProvider();
            if (!typeProvider.Mappings.ContainsKey(".woff2"))
            {
                typeProvider.Mappings.Add(".woff2", "application/font-woff2");
            }
            staticFileOptions.ContentTypeProvider = typeProvider;

            app.UseStaticFiles(staticFileOptions);
            app.UseMvc();
            app.UseApplicationInsightsExceptionTelemetry();
        }
Example #54
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //load application-wide memory store
            Server server = new Server();

            //use session
            app.UseSession();

            //handle static files
            var options = new StaticFileOptions {ContentTypeProvider = new FileExtensionContentTypeProvider()};
            app.UseStaticFiles(options);

            //exception handling
            var errOptions = new DeveloperExceptionPageOptions();
            errOptions.SourceCodeLineCount = 10;
            app.UseDeveloperExceptionPage();

            //get server info from config.json
            checkForConfig();

            var config = new ConfigurationBuilder()
                .AddJsonFile(server.MapPath("config.json"))
                .AddEnvironmentVariables().Build();

            server.sqlActive = config.GetSection("Data:Active").Value;
            server.sqlConnection = config.GetSection("Data:" + server.sqlActive).Value;
            server.https = config.GetSection("https").Value.ToLower() == "true" ? true : false;

            var isdev = false;
            switch (config.GetSection("Environment").Value)
            {
                case "development": case "dev":
                    server.environment = Server.enumEnvironment.development;
                    isdev = true;
                    break;
                case "staging": case "stage":
                    server.environment = Server.enumEnvironment.staging;
                    break;
                case "production": case "prod":
                    server.environment = Server.enumEnvironment.production;
                    break;
            }

            //configure server security
            server.bcrypt_workfactor = int.Parse(config.GetSection("Encryption:bcrypt_work_factor").Value);
            server.CheckAdminPassword();

            //run Websilk application
            app.Run(async (context) =>
            {
                var requestStart = DateTime.Now;
                DateTime requestEnd;
                TimeSpan tspan;
                var requestType = "";
                var path = cleanPath(context.Request.Path.ToString());
                var paths = path.Split('/').Skip(1).ToArray();
                var extension = "";

                //get request file extension (if exists)
                if(path.IndexOf(".")>= 0)
                {
                    for (int x = path.Length - 1; x >= 0; x += -1)
                    {
                        if (path.Substring(x, 1) == ".")
                        {
                            extension = path.Substring(x + 1); return;
                        }
                    }
                }

                server.requestCount += 1;
                if (isdev)
                {
                    Console.WriteLine("--------------------------------------------");
                    Console.WriteLine("{0} GET {1}", DateTime.Now.ToString("hh:mm:ss"), context.Request.Path);
                }

                if (paths.Length > 1)
                {
                    if(paths[0]=="api")
                    {
                        //run a web service via ajax (e.g. /api/namespace/class/function)
                         IFormCollection form = null;
                        if(context.Request.ContentType != null)
                        {
                            if (context.Request.ContentType.IndexOf("application/x-www-form-urlencoded") >= 0)
                            {
                            }else if (context.Request.ContentType.IndexOf("multipart/form-data") >= 0)
                            {
                                //get files collection from form data
                                form = await context.Request.ReadFormAsync();
                            }
                        }

                        if (cleanNamespace(paths))
                        {
                            //execute web service
                            var ws = new Pipeline.WebService(server, context, paths, form);
                            requestType = "service";
                        }
                    }
                }

                if(requestType == "" && extension == "")
                {
                    //initial page request
                    var r = new Pipeline.PageRequest(server, context);
                    requestType = "page";
                }

                if (isdev)
                {
                    requestEnd = DateTime.Now;
                    tspan = requestEnd - requestStart;
                    server.requestTime += (tspan.Seconds);
                    Console.WriteLine("END GET {0} {1} ms {2}", context.Request.Path, tspan.Milliseconds, requestType);
                    Console.WriteLine("");
                }

            });
        }
Example #55
0
        public void Configuration(IAppBuilder builder)
        {
            var rootDirectory = Environment.CurrentDirectory;
            var loginDirectory = Path.Combine(rootDirectory, "login");

            var fs = new PhysicalFileSystem(rootDirectory);
            var loginFs = new PhysicalFileSystem(loginDirectory);

            var dfo = new DefaultFilesOptions();
            dfo.DefaultFileNames.Add("index.html");
            dfo.FileSystem = fs;

            var sfo = new StaticFileOptions
                      {
                          FileSystem = fs
                      };
            var loginSfo = new StaticFileOptions
                           {
                               FileSystem = loginFs
                           };

            builder.SetDataProtectionProvider(new DpapiDataProtectionProvider());
            var formsAuthenticationProvider = new FormsAuthenticationProvider();

            formsAuthenticationProvider.OnValidateLogin = context =>
            {
                Console.WriteLine("Validating Login");
                Console.WriteLine("================");
                Console.WriteLine("  Context.AuthType: " + context.AuthenticationType);
                Console.WriteLine("  Context.Identity: " + (context.Identity != null ? context.Identity.Name : "Not set"));
                Console.WriteLine("  Context.Environment:");

                var response = new OwinResponse(context.Environment);

                if (LoginContext.GetIsLoginRequest(context.Environment))
                {
                    // Need to retrieve username and password from environment b/c it doesn't
                    // come through in the context (even though the context constructor accepts them)

                    var username = context.Environment["formsauthn.username"].ToString();
                    var password = context.Environment["formsauthn.password"].ToString();
                    var remember = bool.Parse(context.Environment["formsauthn.remember"].ToString());

                    Console.WriteLine("  Request.Username: "******"  Request.Password: "******"  Request.Remember: " + remember);

                    if (username == password)
                    {
                        var identity = new ClaimsIdentity(
                            new GenericIdentity(username, context.AuthenticationType),
                            new[]
                            {
                                new Claim(ClaimTypes.IsPersistent, remember.ToString())
                            }
                            );

                        // I assumed that this would take care of populating the cookie for me... but not so much.
                        context.Signin(identity);

                        var msg = "Access granted.";
                        Console.WriteLine(msg);
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        return response.Body.WriteAsync(msgBytes, 0, msgBytes.Length);
                    }
                    else
                    {
                        var msg = "Access denied.  Try with username=password";
                        Console.WriteLine(msg);
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        return response.Body.WriteAsync(msgBytes, 0, msgBytes.Length);
                    }
                }
                else
                {
                    foreach (var item in context.Environment)
                    {
                        Console.WriteLine("  {0}={1}",
                                          item.Key,
                                          item.Value != null
                                              ? (item.Value is string ? (string) item.Value : item.Value.GetType().FullName)
                                              : "Not set"
                            );
                    }
                }

                return response.Body.WriteAsync(new byte[] { }, 0, 0);
            };

            builder.UseFormsAuthentication(
                new FormsAuthenticationOptions
                {
                    CookieHttpOnly = true,
                    CookieName = "AuthCookie",
                    CookiePath = "/",
                    CookieSecure = false,
                    LoginPath = "/login/",
                    ExpireTimeSpan = TimeSpan.FromHours(1),
                    ReturnUrlParameter = "returnUrl",
                    SlidingExpiration = true,
                    Provider = formsAuthenticationProvider
                }
            );
            builder.UseApplicationSignInCookie();
            builder.UseDefaultFiles(dfo);
            builder.UseErrorPage();
            builder.MapPath("/login", loginBuilder => loginBuilder.UseProcessLoginPostback(formsAuthenticationProvider).UseStaticFiles(loginSfo));
            builder.UseDenyAnonymous().UseStaticFiles(sfo);
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            string contentPath = Path.Combine(Environment.CurrentDirectory, @"..\..");
            var fileOptions = new StaticFileOptions
            {
                FileSystem = new PhysicalFileSystem(contentPath),
            };

            app.UseStaticFiles(fileOptions);
            loginForm = File.ReadAllBytes(Path.Combine(contentPath, @"Account/form.html"));

            var options = new CookieAuthenticationOptions()
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                LoginPath = CookieAuthenticationDefaults.LoginPath,
                LogoutPath = CookieAuthenticationDefaults.LogoutPath,
            };

            app.UseCookieAuthentication(options);

            app.Use(async (context, next) =>
            {
                var redirectUri = context.Request.Query["ReturnUrl"];

                if(context.Request.Path.Value.Contains(options.LoginPath.Value))
                {
                    if (context.Request.Method == "POST")
                    {
                        var form = await context.Request.ReadFormAsync();
                        var userName = form["UserName"];
                        var password = form["Password"];

                        if (!ValidateUserCredentials(userName, password))
                        {
                            var redirect = options.LoginPath.Value;
                            if (!String.IsNullOrEmpty(redirectUri))
                            {
                                redirect += "?ReturnUrl=" + WebUtility.UrlEncode(redirectUri);
                            }

                            context.Response.Redirect(redirect);
                        }

                        var identity = new ClaimsIdentity(options.AuthenticationType);
                        identity.AddClaim(new Claim(ClaimTypes.Name, userName));
                        context.Authentication.SignIn(identity);

                        redirectUri = redirectUri ?? "/index.html";
                        context.Response.Redirect(redirectUri);
                    }
                    else
                    {
                        context.Response.ContentType = "text/html";
                        await context.Response.WriteAsync(loginForm);
                    }
                }
                else if (context.Request.Path.Value.Contains(options.LogoutPath.Value))
                {
                    context.Authentication.SignOut(options.AuthenticationType);
                    redirectUri = redirectUri ?? options.LoginPath.Value;
                    context.Response.Redirect(redirectUri);
                }
                else if (context.Request.User == null || !context.Request.User.Identity.IsAuthenticated)
                {
                    context.Response.Redirect(options.LoginPath.Value);
                }
                else if (context.Request.Path.Value == "/")
                {
                    context.Response.Redirect("/index.html");
                }
                else
                {
                    await next();
                }
            });

            app.MapSignalR<AuthorizeEchoConnection>("/echo");
            app.MapSignalR();
        }
Example #57
0
        public void ServeUnknownFileTypesConfiguration(IAppBuilder app)
        {
            var staticFileOptions = new StaticFileOptions();

            app.Use((context, next) =>
                {
                    staticFileOptions.ServeUnknownFileTypes = context.Request.Headers.ContainsKey("ServeUnknown") ? true : false;
                    staticFileOptions.DefaultContentType = staticFileOptions.ServeUnknownFileTypes ? "unknown/unknown" : null;
                    return next.Invoke();
                });

            app.UseStaticFiles(staticFileOptions);
        }
Example #58
0
 public void CustomMimeTypeConfiguration(IAppBuilder app)
 {
     var options = new StaticFileOptions();
     (options.ContentTypeProvider as FileExtensionContentTypeProvider).Mappings.Add(".Unknown", "CustomUnknown");
     app.UseStaticFiles(options);
 }
Example #59
0
		/// <summary>
		/// Creates a new instance of the <see cref="BabelFileOptions"/> class.
		/// </summary>
		public BabelFileOptions()
		{
			Extensions = new[] { ".jsx" };
			StaticFileOptions = new StaticFileOptions();
		}
Example #60
0
 public void Configuration(IAppBuilder app)
 {
     var options = new StaticFileOptions();
     options.FileSystem = new EmbeddedResourceFileSystem();
     app.UseStaticFiles(options);
 }