欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET Core静态文件的使用方法

程序员文章站 2023-12-04 23:31:34
前言 静态文件(html,css,图片和javascript之类的资源)会被asp.net core应用直接提供给客户端。 静态文件通常位于网站根目录(web root...

前言

静态文件(html,css,图片和javascript之类的资源)会被asp.net core应用直接提供给客户端。

静态文件通常位于网站根目录(web root) <content-root>/wwwroot文件夹下。通常会把项目的当前目录设置为content root,这样项目的web root就可以在开发阶段被明确。

public static iwebhostbuilder createwebhostbuilder(string[] args) =>
  webhost.createdefaultbuilder(args)
  .usecontentroot(directory.getcurrentdirectory()) //设置当前目录
  .usestartup<startup>();

静态文件能够被保存在网站根目录下的任意文件夹内,并通过相对根的路径来访问。使用vs创建一个默认的web应用程序时,在wwwroot目录下会生成几个文件夹:css,images,js。如果压迫访问images目录下的图片:

  http://<app>/iamges/filename

  https://localhost:44303/iamges/filename

要想使用静态文件服务,必须配置中间件,把静态文件中间件加入到管道。静态文件一般会默认配置,在configure方法中调用app.usestaticfiles()

app.usestaticfiles() 使得web root(默认为wwwroot)下的文件可以被访问。同时可以通过usestaticfiles方法将其他目录下的内容也可以向外提供:

假如wwwroot外面有一个mystaticfiles文件夹,要访问文件夹里面的资源test.png:  

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
 {

  app.usehttpsredirection();
  app.usestaticfiles();
  app.usestaticfiles(new staticfileoptions() {
  fileprovider = new physicalfileprovider(
   path.combine(directory.getcurrentdirectory(), @"mystaticfiles")), //用于定位资源的文件系统
  requestpath = new pathstring("/staticfiles") //请求地址
  });

 }

可以通过访问

  http://<app>/staticfiles/test.png

  https://localhost:44303/staticfiles/test.png

1.静态文件授权

静态文件组件默认不提供授权检查。任何通过静态文件中间件访问的文件都是公开的。要想给文件授权,可以将文件保存在wwwroot之外,并将目录设置为可被静态文件中间件能够访问,同时通过一个controller action来访问文件,在action中授权后返回fileresult。

2.目录浏览

目录浏览允许网站用户看到指定目录下的目录和文件列表。基于安全考虑,默认情况下是禁止目录访问功能。在startup.configure中调用usedirectorybrowser扩展方法可以开启网络应用目录浏览:

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
 {
  app.usestaticfiles();

  app.usedirectorybrowser(new directorybrowseroptions() {
  fileprovider = new physicalfileprovider(
   path.combine(directory.getcurrentdirectory(),@"wwwroot\images")),
  requestpath = new pathstring("/myimages") //如果不指定requestpath,会将physicalfileprovider中的路径参数作为默认文件夹,替换掉wwwroot
}); }

然后在startup.congigureservices中调用adddirectorybrowser扩展方法。

这样就可以通过访问http://<app>/myimages浏览wwwroot/images文件夹中的目录,但是不能访问文件:

ASP.NET Core静态文件的使用方法  

要想访问具体文件需要调用usestaticfiles配置: 

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
 {
  app.usestaticfiles();
  app.usestaticfiles(new staticfileoptions() {
  fileprovider = new physicalfileprovider(
   path.combine(directory.getcurrentdirectory(), @"wwwroot\images")), //用于定位资源的文件系统
  requestpath = new pathstring("/myimages")
  });
  app.usedirectorybrowser(new directorybrowseroptions() {
  fileprovider = new physicalfileprovider(
   path.combine(directory.getcurrentdirectory(),@"wwwroot\images")),
  requestpath = new pathstring("/myimages")
  });

 }

3.默认文件

设置默认首页能给站点的访问者提供一个起始页,在startup.configure中调用usedefafiles扩展方法:

  app.usedefaultfiles(options);
  app.usestaticfiles(); 

usedefaultfiles必须在usestaticfiles之前调用。usedefaultfiles只是重写了url,而不是真的提供了一个这样的文件,浏览器url将继续显示用户输入的url。所以必须开启静态文件中间件。而且默认文件必须放在静态文件中间件可以访问得到的地方,默认是wwwroot中。

通过usedefaultfiles,请求文件夹的时候检索以下文件:

  default.htm

  default.html

  index.htm

  index.html

也可以使用usedefaultfiles将默认页面改为其他页面:

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
 {
  if (env.isdevelopment())
  {
  app.usedeveloperexceptionpage();
  }
  else
  {
  app.useexceptionhandler("/home/error");
  app.usehsts();
  }

  app.usehttpsredirection();
  defaultfilesoptions options = new defaultfilesoptions();
  options.defaultfilenames.clear();
  options.defaultfilenames.add("mydefault.html");
  app.usedefaultfiles(options);
  app.usestaticfiles();


  app.usemvc(routes =>
  {
  routes.maproute(
   name: "default",
   template: "{controller=home}/{action=index}/{id?}");
  });
 }

4.usefileserver

usefileserver集合了usestaticfiles,usedefaultfiles,usedirectorybrowser。

调用app.usefileserver(); 请用了静态文件和默认文件,但不允许直接访问目录。需要调用app.usefileserver(enabledirectorybrowsing:true); 才能启用目录浏览功能。

如果想要访问wwwroot以外的文件,需要配置一个fileserveroptions对象 

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
 {       app.usestaticfiles();//如果不调用,将不会启动默认功能。
  app.usefileserver(new fileserveroptions()
  {
  fileprovider = new physicalfileprovider(
   path.combine(directory.getcurrentdirectory(), @"mystaticfiles")),
  requestpath = new pathstring("/staticfiles"),
  enabledirectorybrowsing = true
  });
}

注意,如果将enabledirectorybrowsing设置为true,需要在configureservices中调用services.adddirectorybrowser();

如果默认文件夹下有默认页面,将显示默认页面,而不是目录列表。

5.fileextensioncontenttypeprovider

fileextensioncontenttypeprovider类包含一个将文件扩展名映射到mime内容类型的集合。

例如:

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
 {
  var provider = new fileextensioncontenttypeprovider();
  provider.mappings[".htm3"] = "text/html";
  provider.mappings["images"] = "iamge/png";
  provider.mappings.remove(".mp4");

  app.usestaticfiles(new staticfileoptions() {
  fileprovider = new physicalfileprovider(
   path.combine(directory.getcurrentdirectory(), @"mystaticfiles")),
  requestpath = new pathstring("/staticfiles"),
  contenttypeprovider = provider
  });
}

更多mime类型可以访问:http://www.iana.org/assignments/media-types/media-types.xhtml

6.非标准的内容类型

如果用户请求了一个未知的文件类型,静态文件中间件将会返回http 404响应。如果启用目录浏览,则该文件的链接将会被显示,但rui会返回一个http404错误。

使用usestaticfiles方法可以将未知类型作为指定类型处理:

app.usestaticfiles(new staticfileoptions() {
  serveunknownfiletypes = true,
  defaultcontenttype = "application/x-msdownload"
  });

对于未识别的,默认为application/x-msdownload,浏览器将会下载这些文件。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。