c# .Net Core静态文件服务器的新人入门教程

 更新时间:2021年9月22日 10:02  点击:1647

概要:

本文通过示例,讲解了 NET Core2.0 静态文件目录的相关知识,并附带解析,适合新手,并附带了完整的项目代码。(项目通过 vs2017 初始化的 ASP.NET Core 应用程序,之后选择***空项目***)

示例代码

项目结构

program.cs文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace StaticFileServer
{
 public class Program
 {
 public static void Main(string[] args)
 {
  BuildWebHost(args).Run();
 }

 public static IWebHost BuildWebHost(string[] args) =>
  WebHost.CreateDefaultBuilder(args)
  .UseKestrel()
  .UseContentRoot(Directory.GetCurrentDirectory()) // 设置当前目录的内容
  .UseIISIntegration()
  .UseUrls("http://*:5000") // 使 项目在 5000端口被访问
  .UseStartup<Startup>()
  .Build();
 }
}

Startup.cs 文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace StaticFileServer
{
 public class Startup
 {
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
  
 }

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
  app.UseStaticFiles(); // 使用默认文件夹 wwwroot 仅仅shi wwwroot对外可见
  
  app.Run(async (context) => 
  {
  await context.Response.WriteAsync("hello jesus");
  });
 }
 }
}

运行效果:

解析: 这是一个基本的静态文件服务器,app.UseStaticFiles() 函数使当前内容目录下默认的 wwwroot中的文件可以被访问

那么问题来了,若想访问其他目录下的静态文件,该怎么办?

设置任意目录下的静态文件可以访问代码:

 // 设置 指定目录的文件 可以被访问 start
  var staticfile = new StaticFileOptions();
  staticfile.FileProvider = new PhysicalFileProvider(@"C:\"); // 指定目录,这里指的是C盘,也可以指定其他目录
  app.UseStaticFiles(staticfile); 

我们吧startup.cs的***Configure*** 函数代码改为如下代码(增加了c盘文件可以访问):

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
  var staticfile = new StaticFileOptions();
  staticfile.FileProvider = new PhysicalFileProvider(@"C:\"); // 指定目录,这里指的是C盘,也可以指定其他目录
  app.UseStaticFiles(staticfile); // 使用默认文件夹 wwwroot 仅仅shi wwwroot对外可见
  
  app.Run(async (context) => 
  {
  await context.Response.WriteAsync("hello jesus");
  });
 }

c盘文件展示

运行效果

这样我们就可以访问任意目录下的文件了,那么问题来了,c盘中有个 叫 456.log 的文件,我们访问不了,原因是:服务器不能识别,怎么办?如何让服务器识别 所有类型的文件呢?  我们以 .log 为后缀的文件为例

我们将***Configure*** 改为一下内容:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
  var staticfile = new StaticFileOptions();
  staticfile.FileProvider = new PhysicalFileProvider(@"C:\"); // 指定目录,这里指的是C盘,也可以指定其他目录

  // 设置 对应的文件类型(防止Mime type没事别出来,打不开或出现404错误)
  staticfile.ServeUnknownFileTypes = true;
  staticfile.DefaultContentType = "application/x-msdownload";// 设置默认 MIME TYPE
  var provider = new FileExtensionContentTypeProvider();
  provider.Mappings.Add(".log", "text/plain"); // 手动设置对应的 MIME TYPE
  staticfile.ContentTypeProvider = provider;

  app.UseStaticFiles(staticfile); // 使用默认文件夹 wwwroot 仅仅shi wwwroot对外可见
  // 设置 指定目录的文件 可以被访问 end

  app.Run(async (context) =>
  {
  await context.Response.WriteAsync("hello jesus");
  });
 }

我们将不能识别的文件类型默认为 : "application/x-msdownload",即遇到我们没处理的,不能识别的类型统统下载下来。

provider.Mappings.Add(".log", "text/plain"); // 手动设置对应的 MIME TYPE 。我们手动增加了 对后缀为.log的文件类型的处理,当成文本文件处理,即txt处理。

运行效果

未知的文件 (我们访问789.ggg文件,此文件类型我们未处理过)

已处理的文件类型

这样,我们就可以访问任意类型的静态文件了,那么问题又来了, 我想访问一个目录下所有的文件,即访问某个目录怎么办?

在 NET Core 中访问目录的功能默认是禁止的,需要手动开启。

步骤:

1、在 ConfigureServices 函数中增加 目录访问服务,

 public void ConfigureServices(IServiceCollection services)
  {
   services.AddDirectoryBrowser(); // 使目录可以被浏览 (浏览所有的文件以及文件夹)
  }

2、在Configure 函数中增加 中间键 和 具体的目录,在这里我们让 c盘下的所有目录可以被访问

 // 设置 目录可浏览 start
   var dir = new DirectoryBrowserOptions();
   dir.FileProvider = new PhysicalFileProvider(@"C:\");
   app.UseDirectoryBrowser(dir);
   // 设置 目录可浏览 end

这样我们就可以访问c盘中的任意目录了,效果如下:

Startup.cs 文件最终代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace StaticFileServer
{
 public class Startup
 {
  // This method gets called by the runtime. Use this method to add services to the container.
  // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  public void ConfigureServices(IServiceCollection services)
  {
   services.AddDirectoryBrowser(); // 使目录可以被浏览 (浏览所有的文件以及文件夹)
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
   // 设置 目录可浏览 start
   var dir = new DirectoryBrowserOptions();
   dir.FileProvider = new PhysicalFileProvider(@"C:\");
   app.UseDirectoryBrowser(dir);
   // 设置 目录可浏览 end

   // 设置 指定目录的文件 可以被访问 start
   var staticfile = new StaticFileOptions();
   staticfile.FileProvider = new PhysicalFileProvider(@"C:\"); // 指定目录,这里指的是C盘,也可以指定其他目录

    // 设置 对应的文件类型(防止Mime type没事别出来,打不开或出现404错误)
    staticfile.ServeUnknownFileTypes = true;
    staticfile.DefaultContentType = "application/x-msdownload";// 设置默认 MIME TYPE
    var provider = new FileExtensionContentTypeProvider();
    provider.Mappings.Add(".log", "text/plain"); // 手动设置对应的 MIME TYPE
    staticfile.ContentTypeProvider = provider;

   app.UseStaticFiles(staticfile); // 使用默认文件夹 wwwroot 仅仅shi wwwroot对外可见
   // 设置 指定目录的文件 可以被访问 end

   app.Run(async (context) => 
   {
    await context.Response.WriteAsync("hello jesus");
   });
  }
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对猪先飞的支持。

[!--infotagslink--]

相关文章

  • .NET Core下使用Kafka的方法步骤

    这篇文章主要介绍了.NET Core下使用Kafka的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 分享一段php获取linux服务器状态的代码

    简单的php获取linux服务器状态的代码,不多说-直接上函数:复制代码 代码如下:function get_used_status(){ $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况 $rs =...2014-05-31
  • 详解.NET Core 3.0 里新的JSON API

    这篇文章主要介绍了详解.NET Core 3.0 里新的JSON API,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • ASP.NET Core根据环境变量支持多个 appsettings.json配置文件

    这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 服务器 UDP端口占用几千个的解决办法

    前一段时间使用NetStat命令查看服务器端口时,发现服务器udp端口开放了好多,最少在1000个以上,当时事情比较多,没有管它,今天终于有点时间,仔细检查了一下,排除了这个问题. ...2016-01-27
  • 记一次EFCore类型转换错误及解决方案

    这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
  • PHP连接公司内部服务器的MYSQL数据库的简单实例

    “主机,用户名,密码”得到连接、“数据库,sql,连接”得到结果,最后是结果的处理显示。当然,数据库连接是扩展库为我们完成的,我们能做的仅仅是处理结果而已。...2013-09-29
  • 解决HttpPost+json请求---服务器中文乱码及其他问题

    这篇文章主要介绍了解决HttpPost+json请求---服务器中文乱码及其他问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-22
  • 详解ASP.NET Core 中基于工厂的中间件激活的实现方法

    这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • IIS7、iis7.5中禁止缓存单个静态文件的配置方法

    这篇文章主要介绍了IIS7、iis7.5中禁止缓存单个静态文件的配置方法,需要的朋友可以参考下...2017-07-06
  • Underscore源码分析

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。这篇文章主要介绍了underscore源码分析相关知识,感兴趣的朋友一起学习吧...2016-01-02
  • uploader秒传图片到服务器完整代码

    这篇文章主要为大家详细介绍了uploader秒传图片到服务器的完整代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-04-27
  • Hyper-V尝试连接到服务器出错无效类的解决方法

    这篇文章主要介绍了Hyper-V尝试连接到服务器出错无效类的解决方法,需要的朋友可以参考下...2016-09-28
  • mac使用Shell(终端)SSH连接远程服务器的方法

    这篇文章主要介绍了mac使用Shell(终端)SSH连接远程服务器的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-07-11
  • 详解.NET Core 使用HttpClient SSL请求出错的解决办法

    这篇文章主要介绍了.NET Core 使用HttpClient SSL请求出错的解决办法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2021-09-22
  • js实现上传图片到服务器

    这篇文章主要为大家详细介绍了js实现上传图片到服务器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-04-11
  • c# HttpWebRequest通过代理服务器抓取网页内容应用介绍

    在C#项目开发过程中可能会有些特殊的需求比如:用HttpWebRequest通过代理服务器验证后抓取网页内容,要想实现此方法并不容易,本文整理了一下,有需求的朋友可以参考下...2020-06-25
  • Linux环境下nginx搭建简易图片服务器

    这篇文章主要介绍了Linux环境下nginx搭建简易图片服务器,需要的朋友可以参考下...2016-01-27
  • 图文详解本地Windows 7/8上IIS服务器搭建教程

    这篇文章主要以图文结合的方式详细介绍了本地Windows 78上IIS服务器搭建教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 ...2017-07-06