public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddMvc(options => { options.EnableEndpointRouting = false; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddSingleton<IConfiguration>(Configuration); //配置跨域处理,允许所有来源: services.AddCors(options => options.AddPolicy("ALL", p => p.AllowAnyOrigin()) ); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCors("ALL"); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "images"))) { Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "images")); } app.UseStaticFiles(new StaticFileOptions { //指定实际物理路径 FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "images")), //设置URL请求的文件路径 RequestPath = new PathString("/images") }); app.UseMvc(); }
使用UseStaticFiles 这个默认中间件时,需要引入上图的nuget包,不然服务加了也访问不到对应wwwroot下的静态文件
若需要额外文件夹访问权限时,可根据需要自定义UseStaticFiles 的文件路径
若出现跨域访问问题,可增加
services.AddCors(options =>
options.AddPolicy("ALL", p => p.AllowAnyOrigin())
);
处理,并注册使用该策略即可(app.UseCors("ALL"))