当下.Net Core项目可是如雨后春笋一般发展起来,作为.Net大军中的一员,我热忱地拥抱了.Net Core并且积极使用其进行业务的开发,我们先介绍下.Net Core项目下实现文件上传下载接口。
一、开发环境
毋庸置疑,宇宙第一IDE VisualStudio 2017
二、项目结构
FilesController 文件上传下载控制器
PictureController 图片上传下载控制器
Return_Helper_DG 返回值帮助类
三、关键代码
1、首先我们来看Startup.cs 这个是我们的程序启动配置类,在这里我们进行一系列的配置。
跨域配置:
当然跨域少不了dll的引用,我们使用Nuget引用相关的引用包
服务器资源路径置换,这样可以防止客户端猜测服务端文件路径,制造一个虚拟的隐射进行访问,提高了安全性。
Startup.cs的完整代码如下:
1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.AspNetCore.Hosting; 3 using Microsoft.AspNetCore.Http; 4 using Microsoft.Extensions.Configuration; 5 using Microsoft.Extensions.DependencyInjection; 6 using Microsoft.Extensions.FileProviders; 7 using Microsoft.Extensions.Logging; 8 using System.IO; 9 10 namespace QX_Core.FilesCenter 11 { 12 public class Startup 13 { 14 public Startup(IHostingEnvironment env) 15 { 16 var builder = new ConfigurationBuilder() 17 .SetBasePath(env.ContentRootPath) 18 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 19 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 20 .AddEnvironmentVariables(); 21 Configuration = builder.Build(); 22 } 23 24 public IConfigurationRoot Configuration { get; } 25 26 // This method gets called by the runtime. Use this method to add services to the container. 27 public void ConfigureServices(IServiceCollection services) 28 { 29 // Add framework services. 30 services.AddMvc(); 31 #region CORS 32 services.AddCors(options => 33 { 34 options.AddPolicy("AllowSpecificOrigin", 35 builder => builder.WithOrigins("http://localhost:3997").AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod()); 36 }); 37 #endregion 38 } 39 40 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 41 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 42 { 43 //loggerFactory.AddConsole(Configuration.GetSection("Logging")); 44 //loggerFactory.AddDebug(); 45 46 app.UseMvc(); 47 // Shows UseCors with named policy. 48 app.UseCors("AllowSpecificOrigin"); 49 50 app.UseStaticFiles(new StaticFileOptions() 51 { 52 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Files")), 53 RequestPath = new PathString("/src") 54 }); 55 } 56 } 57<