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

所属分类: 网络编程 / ASP.NET 阅读数: 547
收藏 0 赞 0 分享

概要:

本文通过示例,讲解了 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");
   });
  }
 }
}

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

更多精彩内容其他人还在看

开源跨平台运行服务插件TaskCore.MainForm

这篇文章主要为大家详细介绍了开源跨平台运行服务插件TaskCore.MainForm的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

CKEditor自定义按钮插入服务端图片

这篇文章主要为大家详细介绍了CKEditor自定义按钮插入服务端图片的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Asp.net Web Api实现图片点击式图片验证码功能

现在验证码的形式越来越丰富,今天要实现的是在点击图片中的文字来进行校验的验证码。下面通过本文给大家分享Asp.net Web Api实现图片点击式图片验证码功能,需要的的朋友参考下吧
收藏 0 赞 0 分享

WPF实现ScrollViewer滚动到指定控件处

这篇文章主要为大家详细介绍了WPF实现ScrollViewer滚动到指定控件处,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

WPF实现带全选复选框的列表控件

这篇文章主要为大家详细介绍了WPF实现带全选复选框的列表控件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Asp.net MVC 中利用jquery datatables 实现数据分页显示功能

这篇文章主要介绍了Asp.net MVC 中利用jquery datatables 实现数据分页显示功能,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

asp.net 利用NPOI导出Excel通用类的方法

本篇文章主要介绍了asp.net 利用NPOI导出Excel通用类的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

VS2015自带LocalDB数据库用法详解

这篇文章主要为大家详细介绍了VS2015自带LocalDB数据库的用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SignalR Self Host+MVC等多端消息推送服务(一)

这篇文章主要为大家详细介绍了SignalR Self Host+MVC等多端消息推送服务,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SignalR Self Host+MVC等多端消息推送服务(二)

这篇文章主要为大家详细介绍了SignalR Self Host+MVC等多端消息推送服务的第二篇,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多