Processing of static file requests by ASP. NET Core applications [5]: ultfilesmiddleware how to display the default page,

Source: Internet
Author: User

Processing of static file requests by ASP. NET Core applications [5]: ultfilesmiddleware how to display the default page,

DefaultFilesMiddleware middleware aims to use the default file in the target directory as the response content. We know that if the default file is directly requested, the StaticFileMiddleware middleware described above will send the file to the client. If we can redirect requests for directories to this default file, everything will be solved. In fact, the implementation logic of DefaultFilesMiddleware middleware is very simple. It uses URL rewriting to modify the address of the current request, that is, to change the URL for the directory to the URL for the default file. [This Article has been synchronized to ASP. NET Core framework secrets]

Let's take a look at the definition of the DefaultFilesMiddleware type as an example. Similar to the other two middleware, The DefaultFilesMiddleware structure has an IOptions <defafilefilesoptions> parameter to specify related configuration options. Because DefaultFilesMiddleware middleware still essentially reflects the ing between the request path and a physical directory, DefaultFilesOptions is still derived from SharedOptionsBase. ).

   1: public class DefaultFilesMiddleware
   2: {
   3:     public DefaultFilesMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, IOptions<DefaultFilesOptions> options);
   4:     public Task Invoke(HttpContext context);
   5: }
   6:  
   7: public class DefaultFilesOptions : SharedOptionsBase
   8: {
   9:     public IList<string> DefaultFileNames { get; set; }
  10:  
  11:     public DefaultFilesOptions() : this(new SharedOptions()){}
  12:     public DefaultFilesOptions(SharedOptions sharedOptions) : base(sharedOptions)
  13:     {
  14:         this.DefaultFileNames = new List<string> { "default.htm", "default.html", "index.htm", "index.html" };
  15:     }    
  16: }

We also redefine the DefaultFilesMiddleware type in an easy-to-understand way to help readers understand the specific request processing logic it uses. As shown in the following code snippet, DefaultFilesMiddleware and DirectoryBrowserMiddleware verify the request accordingly. If a default file exists in the current directory, the requested URL is changed to the URL pointing to the default file. It is worth mentioning that the DefaultFilesMiddleware middleware requires that the Request Path to access the directory must be suffixed with the character, otherwise, the suffix will be added to the current path and a redirection will be sent for the final path.

   1: public class DefaultFilesMiddleware
   2: {
   3:     private RequestDelegate         _next;
   4:     private DefaultFilesOptions     _options;
   5:   
   6:     public DefaultFilesMiddleware(RequestDelegate next, IHostingEnvironment env, IOptions<DefaultFilesOptions> options)
   7:     {
   8:         _next                     = next;
   9:         _options                  = options.Value;
  10:         _options.FileProvider     = _options.FileProvider ?? env.WebRootFileProvider;
  11:     }
  12:  
  13:     public async Task Invoke(HttpContext context)
  14:     {
15: // only GET and HEAD requests are processed
  16:         if (!new string[] { "GET", "HEAD" }.Contains(context.Request.Method,StringComparer.OrdinalIgnoreCase))
  17:         {
  18:             await _next(context);
  19:             return;
  20:         }
  21:  
22: // check whether the current path matches the registered Request Path
  23:         PathString path = new PathString(context.Request.Path.Value.TrimEnd('/') + "/");
  24:         PathString subpath;
  25:         if (!path.StartsWithSegments(_options.RequestPath, out subpath))
  26:         {
  27:             await _next(context);
  28:             return;
  29:         }
  30:  
31: // check whether the target directory exists
  32:         if (!_options.FileProvider.GetDirectoryContents(subpath).Exists)
  33:         {
  34:             await _next(context);
  35:             return;
  36:         }
  37:  
38: // check whether the current directory contains the default file
  39:         foreach (var fileName in _options.DefaultFileNames)
  40:         {
  41:             if (_options.FileProvider.GetFileInfo($"{subpath}{fileName}").Exists)
  42:             {
43: // if the current path does not use "/" as the suffix, A redirection for the "standard" URL will be returned.
  44:                 if (!context.Request.Path.Value.EndsWith("/"))
  45:                 {
  46:                     context.Response.StatusCode = 302;
  47:                     context.Response.GetTypedHeaders().Location = new Uri(path.Value + context.Request.QueryString);
  48:                     return;
  49:                 }
50: // update the URL for the directory to the URL for the default file
  51:                 context.Request.Path = new PathString($"{context.Request.Path}{fileName}");
  52:             }
  53:         }
  54:         await _next(context);
  55:     }
  56: }

It is precisely because DefaultFilesMiddleware middleware uses URL rewriting to respond to the default file, so it finally relies on StaticFileMiddleware middleware to respond to the default file, so it is required for the latter's registration. This is also the reason. This middleware needs to register first to ensure that URL rewriting occurs before the StaticFileMiddleware response file.

Processing of static file requests by ASP. NET Core applications [1]: publishing static files in the form of Web
Processing of static file requests by ASP. NET Core applications [2]: Conditional requests and interval requests
Processing of static file requests by ASP. NET Core applications [3]: How does StaticFileMiddleware process file requests?
Processing of static file requests by ASP. NET Core applications [4]: How does DirectoryBrowserMiddleware display the directory structure?
Processing of static file requests by ASP. NET Core applications [5]: ultfilesmiddleware how to display the default page

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.