Parse how to use an ASP. NET Core application to publish static files, asp. netcore
Although ASP. NET Core is a "dynamic" Web Server framework, but in many cases, it needs to process requests for static files, the most common request is for JavaScript script files, CSS style files, and image files. ASP. NET Core provides three middleware for processing static file requests in different formats. They will be the focus of this series of articles. However, before introducing them, we can use some simple examples to see how to publish static files in an ASP. NET Core application.
Directory
1. Reading files on the Web
Ii. Browse Contents
3. display the default page
Iv. ing media types
1. Reading files on the Web
The demo instance we created is a simple ASP. NET Core console application with the project structure shown in. We can see that under the default WebRoot directory (wwwroot), we store JavaScript script files, CSS style files, and image files in the corresponding subdirectories (js, css, and img, we will publish all the files in this directory in the form of Web, and the client can access the corresponding URL to obtain these files.
Requests for static files are implemented through a middleware named StaticFileMiddleware. This middleware type is defined in the NuGet package "Microsoft. aspNetCore. staticFiles, so we need to follow this NuGet package in advance. The entire application only contains the following lines of code. The registration of StaticFileMiddleware middleware is completed by calling the extended method UseStaticFiles of ApplicationBuilder.
public class Program { public static void Main() { new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .Configure(app => app.UseStaticFiles()) .Build() .Run(); } }
In addition to registering the required StaticFileMiddleware middleware, we also call the UseContentRoot method of WebHostBuilder to use the root directory of the current project as the ContentRoot directory. We know that ASP. NET Core applications have two important root directories: ContentRoot and WebRoot. The latter is also the default root directory for externally published static files. Because the default path of the WebRoot directory is "{contentroot}/wwwroot", the above program is to publish all the static files under the wwwroot directory in the project.
After the program runs, we can get a file by sending an HTTP request to the corresponding URL, which is determined by the path of the file equivalent to the wwwroot directory. For example, JPG file "~ The URL corresponding to/wwwroot/img/dophin1.jpg is "http ://
Localhost: 5000/img/dophin1.jpg ". We directly access this URL using a browser, and the target image will be displayed directly.
In the preceding example, all static files in the WebRoot directory are directly published. What if the static files to be released are stored in other directories? This application is still demonstrated. Now we store some documents in the "~ /Doc/"directory and released in the form of Web, how should we write our program?
We know that most ASP. NET Core applications use a FileProvider object to read files. It is no exception in processing requests for static files. For the middleware registered by calling the extended method UseStaticFiles of ApplicationBuilder, StaticFileMiddleware has a fileing relationship between FileProvider and Request Path. If the UseStaticFiles method is called without specifying any parameters, the Request Path for this ing relationship is the application's base address (PathBase), and FileProvider is naturally the PhysicalFileProvider pointing to the WebRoot directory.
The preceding requirement can be implemented by explicitly registering this ing. Therefore, we have added an additional call to the UseStaticFiles method based on the existing program, the specified parameter (which is a StaticFileOptions object) explicitly specifies the FileProvider /Doc/"PhysicalFileProvider) and Request Path ("/documents ").
public class Program { public static void Main() { string contentRoot = Directory.GetCurrentDirectory(); new WebHostBuilder() .UseContentRoot(contentRoot) .UseKestrel() .Configure(app => app .UseStaticFiles() .UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(contentRoot, "doc")), RequestPath = "/documents" })) .Build() .Run(); } }
According to the ing relationships specified in the above section, The Upload File ({checklist}") in the/doc/examples directory. The URL published on the Web is "http: // localhost: 5000/documents/checklistparts ". When we request this address in a browser, the content of the PDF file will be displayed in the browser as shown in.
Ii. Browse Contents
The registered StaticFileMiddleware middleware only processes requests for a specific static file. If we send an HTTP request to the URL of a directory (such as "http: // localhost: 5000/img/"), the response is 404. However, you can register another middleware named DirectoryBrowserMiddleware to display the contents of the Request directory. Specifically, this middleware will return an HTML page, and all files in the request directory will be included in this page as tables. For the application we demonstrated, we can call the UseDirectoryBrowser method as follows to register this DirectoryBrowserMiddleware middleware.
public class Program { public static void Main() { string contentRoot = Directory.GetCurrentDirectory(); IFileProvider fileProvider = new PhysicalFileProvider( Path.Combine(contentRoot, "doc")); new WebHostBuilder() .UseContentRoot(contentRoot) .UseKestrel() .Configure(app => app .UseStaticFiles() .UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider, RequestPath = "/documents" }) .UseDirectoryBrowser() .UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = fileProvider, RequestPath = "/documents" })) .Build() .Run(); } }
After the above application is started, if we use a browser to send a URL (such as "http: // localhost: 5000/" or "http: // localhost: 5000/img/"), the contents of the target directory (including subdirectories and files) will be displayed in the form shown in a table. In addition, subdirectories and files are displayed as links to the URLs of the target directory or file.
3. display the default page
In terms of security, using the registered UseDirectoryBrowser middleware to display a directory browsing page exposes all interfaces and all files in the target directory, therefore, this middleware should be used with caution based on its own security policies. Another more common response policy for directory requests is to display a default page saved in this directory. According to the Conventions, the following four naming methods are generally used as the objects page: default.htm?default.html#index.htm=index.html. The rendering of the inventory page in the target directory is implemented in a middleware named DefaultFilesMiddleware. The application we demonstrate can call the UseDefaultFiles method to register this middleware as follows.
public class Program { public static void Main() { string contentRoot = Directory.GetCurrentDirectory(); IFileProvider fileProvider = new PhysicalFileProvider(Path.Combine(contentRoot, "doc")); new WebHostBuilder() .UseContentRoot(contentRoot) .UseKestrel() .Configure(app => app .UseDefaultFiles() .UseDefaultFiles(new DefaultFilesOptions{ RequestPath = "/documents", FileProvider = fileProvider, }) .UseStaticFiles() .UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider, RequestPath = "/documents" }) .UseDirectoryBrowser() .UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = fileProvider, RequestPath = "/documents" })) .Build() .Run(); } }
Now we are Create a default page named index.htm under the/wwwroot/img/tutorial directory. Now, you can access the corresponding URL ("http: // localhost: 5000/img/") in the browser /"), displays the content of this page.
We must register DefaultFilesMiddleware before registering StaticFileMiddleware and DirectoryBrowserMiddleware; otherwise, it will not work. DirectoryBrowserMiddleware and DefaultFilesMiddleware both process directory requests. If DirectoryBrowserMiddleware is registered first, the contents of the Directory are always displayed. If DefaultFilesMiddleware is registered first, the contents of the directory will be displayed if the default page does not exist. As to why DefaultFilesMiddleware should be registered before StaticFileMiddleware, the latter is implemented by URL rewriting. That is to say, this middleware will rewrite the requests for directories to the response page, in the end, the requests on the response page must depend on StaticFileMiddleware.
In the current request directory. If we hope that the file on the webpage cannot follow the naming conventions (such as readme.htm), we need to explicitly specify the file name on the webpage as follows.
public class Program { public static void Main() { string contentRoot = Directory.GetCurrentDirectory(); IFileProvider fileProvider = new PhysicalFileProvider(Path.Combine(contentRoot, "doc")); DefaultFilesOptions options1 = new DefaultFilesOptions(); DefaultFilesOptions options2 = new DefaultFilesOptions{ RequestPath = "/documents", FileProvider = fileProvider }; options1.DefaultFileNames.Add("readme.htm"); options2.DefaultFileNames.Add("readme.htm"); new WebHostBuilder() .UseContentRoot(contentRoot) .UseKestrel() .Configure(app => app .UseDefaultFiles(options1) .UseDefaultFiles(options2) .UseStaticFiles() .UseStaticFiles(new StaticFileOptions{ FileProvider = fileProvider, RequestPath = "/documents" }) .UseDirectoryBrowser() .UseDirectoryBrowser(new DirectoryBrowserOptions{ FileProvider = fileProvider, RequestPath = "/documents" })) .Build() .Run(); } }
Iv. ing media types
The example shown above shows that the browser can correctly display the content of the target file of the request. Anyone who has a basic understanding of the HTTP protocol should be aware that the presentation of response files on supported browsers has a basic premise, that is, the media Type carried by the response message through the Content-Type Header must be consistent with the Content. Our example demonstrates two types of file requests: JPG files and PDF files, the corresponding media types are "image/jpg" and "application/pdf". How does StaticFileMiddleware correctly parse the correct media types?
StaticFileMiddleware resolves media types through an object named ContentTypeProvider. By default, it uses a FileExtensionContentTypeProvider object. As the name suggests, FileExtensionContentTypeProvider resolves the media type based on the extension name of the file. FileExtensionContentTypeProvider has predefined mappings between several hundred common file extensions and the corresponding media types. Therefore, if the released static file has a standard extension, staticFileMiddleware can assign the correct media type to the corresponding response.
So if the extension of a file is not in this predefined ing, Or we need a predefined extension to match different media types, what should we do? For the instance we demonstrated, I want to Change the file name extension of/wwwroot/img/dophin1.jpg to ". img". Without a doubt, StaticFileMiddleware can parse the correct media type for requests to the file. This problem has several different solutions. The first solution is to enable StaticFileMiddleware to support unrecognized file types and set a default media type for them, the specific programming method is as follows.
public class Program { public static void Main() { new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory();) .UseKestrel() .Configure(app => app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, DefaultContentType = "image/jpg" })) .Build() .Run(); } }
The above solution can only set one default media type. If there are multiple types of non-recognized files that need to be mapped to different media types, this solution is powerless, therefore, the most fundamental solution is to map unrecognized file types and corresponding media types. Since the ContentTypeProvider used by StaticFileMiddleware can be customized, We can explicitly specify a FileExtensionContentTypeProvider object for StaticFileMiddleware as its ContentTypeProvider in the following way, then add the missing ing to the FileExtensionContentTypeProvider object.
public class Program { public static void Main() { FileExtensionContentTypeProvider contentTypeProvider = new FileExtensionContentTypeProvider(); contentTypeProvider.Mappings.Add(".img", "image/jpg"); new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .Configure(app => app.UseStaticFiles(new StaticFileOptions{ ContentTypeProvider = contentTypeProvider })) .Build() .Run(); } }
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message and share it with us!