aspnet / StaticFiles

[Archived] Middleware for handling requests for file system resources including files and directories. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
114 stars 72 forks source link

Simplify configuring file extensions. #161

Closed Tratcher closed 8 years ago

Tratcher commented 8 years ago

129 @muratg @davidfowl @glennc

@DamianEdwards I added sample code for loading extensions from config.

Old sample code:

            var options = new FileServerOptions
            {
                EnableDirectoryBrowsing = true, // Unrelated, but common
            };

            var contentTypes = new FileExtensionContentTypeProvider();
            contentTypes.Mappings[".custom"] = "custom/type";
            contentTypes.Mappings.Remove(".custom");
            options.StaticFileOptions.ContentTypeProvider = contentTypes;

            app.UseFileServer(options);

            var contentTypes = new FileExtensionContentTypeProvider();
            contentTypes.Mappings[".custom"] = "custom/type";
            contentTypes.Mappings.Remove(".custom");

            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = contentTypes,
                OnPrepareResponse = _ => { }
            });

New code:

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context => { },
                ContentTypeProvider = new FileExtensionContentTypeProvider()
                    .SetFileType(".custom", "custom/type")
                    .RemoveFileType(".foo")
            });

            app.UseFileServer(new FileServerOptions
            {
                EnableDirectoryBrowsing = true,
                ContentTypeProvider = new FileExtensionContentTypeProvider()
                    .SetFileType(".custom", "custom/type")
                    .RemoveFileType(".foo")
            });
Tratcher commented 8 years ago

Offline discussion: this saves a few lines of code, but it doesn't solve the discoverability issue around IContentTypeProvider. We'll revisit this in 2.0, possibly by removing/refactoring the abstraction.