.Net Core静态文件服务器学习

转自:https://blog.youkuaiyun.com/ITzhongzi/article/details/80846228
官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2
参考: https://www.cnblogs.com/linezero/p/5541326.html

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

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 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");
            });
        }
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 运行效果:
    这里写图片描述
    解析: 这是一个基本的静态文件服务器,
    app.UseStaticFiles() 函数使当前内容目录下默认的 wwwroot中的文件可以被访问

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

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

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

    我们吧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");
                });
            }
     
     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 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");
                });
            }
     
     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    我们将不能识别的文件类型默认为 : “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(); // 使目录可以被浏览 (浏览所有的文件以及文件夹)
            }
     
     
    • 1
    • 2
    • 3
    • 4
    1. 在Configure 函数中增加 中间键 和 具体的目录,在这里我们让 c盘下的所有目录可以被访问
     // 设置 目录可浏览  start
                var dir = new DirectoryBrowserOptions();
                dir.FileProvider = new PhysicalFileProvider(@"C:\");
                app.UseDirectoryBrowser(dir);
                // 设置 目录可浏览  end
     
     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 这样我们就可以访问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");
                });
            }
        }
    }
    
     
     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
一个基于ASP.NET Core的可伸缩、通用的文件服务器。 通常后端项目可能会有头像、图片、音频、视频等上传/下载需求,这些需求都可以抽象为文件服务。 功能特点 支持Linux(推荐)、Windows 可伸缩式架构,支持部署1-N台文件服务器 RESTful架构的API接口,支持多语言客户端 支持文件秒传、断点续传、远程拉取上传 支持为用户指定磁盘空间配额 支持自定义文件处理器 系统架构 文件的上传/下载通常由客户端直接与文件服务器交互,上传时需要提供代表用户身份token(由业务服务器生成),成功后会返回文件根地址。 也可以直接由业务服务器上传返回文件根地址给客户端。 源码中包含基于.Net Standard的服务端SDK,可以生成token、上传文件等 源码中包含基于.Net Standard的客户端SDK,可以上传/下载文件等 后端使用 配置业务服务器 //Startup.cs代码片段 public void ConfigureServices(IServiceCollection services) { //.... services.AddFileService(opts => { opts.Host = "fs.mondol.info"; //文件服务器域名 opts.AppSecret = "xxxxxx"; //加密密钥,需要与文件服务器相同 }); } 生成访问令牌 IFileServiceManager fileSvceMgr; //此实例可通过DI框架获得 //根据业务规定其意义,例如:1-代表管理员,2-代表用户 var ownerType = 2; var ownerId = 2; //如果ownerType=2,则为用户ID var validTime = TimeSpan.FromDays(2); //token有效期 var ownerToken = fileSvceMgr.GenerateOwnerTokenString(ownerType, ownerId, validTime); 前端使用 文件上传 IFileServiceClient fileClient; //此实例可通过DI框架获得 var ownerToken = "业务服务器返回的token"; var periodMinute = 0; //有效期,0不过期 var updResult = await fileClient.UploadAsync(ownerToken, "文件路径", periodMinute); var url = updResult.Data.Url; //得到文件根地址 标签:文件服务器
一个基于ASP.NET Core的可伸缩、通用的文件服务器。 通常后端项目可能会有头像、图片、音频、视频等上传/下载需求,这些需求都可以抽象为文件服务。 功能特点 支持Linux(推荐)、Windows 可伸缩式架构,支持部署1-N台文件服务器 RESTful架构的API接口,支持多语言客户端 支持文件秒传、断点续传、远程拉取上传 支持为用户指定磁盘空间配额 支持自定义文件处理器 系统架构 Scheme 文件的上传/下载通常由客户端直接与文件服务器交互,上传时需要提供代表用户身份token(由业务服务器生成),成功后会返回文件根地址。 也可以直接由业务服务器上传返回文件根地址给客户端。 源码中包含基于.Net Standard的服务端SDK,可以生成token、上传文件等 源码中包含基于.Net Standard的客户端SDK,可以上传/下载文件等 后端使用 配置业务服务器 //Startup.cs代码片段 public void ConfigureServices(IServiceCollection services) { //.... services.AddFileService(opts => { opts.Host = "fs.mondol.info"; //文件服务器域名 opts.AppSecret = "xxxxxx"; //加密密钥,需要与文件服务器相同 }); } 生成访问令牌 IFileServiceManager fileSvceMgr; //此实例可通过DI框架获得 //根据业务规定其意义,例如:1-代表管理员,2-代表用户 var ownerType = 2; var ownerId = 2; //如果ownerType=2,则为用户ID var validTime = TimeSpan.FromDays(2); //token有效期 var ownerToken = fileSvceMgr.GenerateOwnerTokenString(ownerType, ownerId, validTime); 前端使用 文件上传 IFileServiceClient fileClient; //此实例可通过DI框架获得 var ownerToken = "业务服务器返回的token"; var periodMinute = 0; //有效期,0不过期 var updResult = await fileClient.UploadAsync(ownerToken, "文件路径", periodMinute); var url = updResult.Data.Url; //得到文件根地址 URL格式说明 完整URL格式是这样的:https://domain.com/{fileToken}/{handler}/{modifier} fileToken:是本次上传文件的唯一标识符 handler:文件处理器,可以是image(图片处理器)、video(视频处理器)、raw(返回原文件)等 modifier:【可选】文件处理器参数,例如,image处理器,可以指定128x128_png 文件上传成功后返回的文件根地址(updResult.Data.Url)就是截至到https://domain.com/{fileToken},URL后面部分由客户端自己去拼接 下面举例说明: 下载原文件 文件根地址/raw,例如: http://file.domain.com/files/1iYQTU7fEUgaa~URSVwaCqQKFml_IAAAAAgAAAAbhmsFjiUUQwCPn2ngI1QcvsSp0AA/raw 下载128x128大小的缩略图(原文件是图像) 文件根地址/image/128x128,例如: http://file.domain.com/files/1iYQTU7fEUgaa~URSVwaCqQKFml_IAAAAAgAAAAbhmsFjiUUQwCPn2ngI1QcvsSp0AA/image/128x128 下载128宽,高等比缩放的缩略图(原文件是图像) 文件根地址/image/128x,例如: http://file.domain.com/files/1iYQTU7fEUgaa~URSVwaCqQKFml_IAAAAAgAAAAbhmsFjiUUQwCPn2ngI1QcvsSp0AA/image/128x 原图是JPG格式,下载png格式的图像 文件根地址/image/raw_png,例如: http://file.domain.com/files/1iYQTU7fEUgaa~URSVwaCqQKFml_IAAAAAgAAAAbhmsFjiUUQwCPn2ngI1QcvsSp0AA/image/raw_png 原图是JPG格式,下载png格式的128x128大小的缩略像 文件根地址/image/128x128_png,例如: http://file.domain.com/files/1iYQTU7fEUgaa~URSVwaCqQKFml_IAAAAAgAAAAbhmsFjiUUQwCPn2ngI1QcvsSp0AA/image/128x128_png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值