// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("layout.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); }
/// <summary> /// Creates a new instance of the DefaultFilesMiddleware. /// </summary> /// <param name="next">The next middleware in the pipeline.</param> /// <param name="options">The configuration options for this middleware.</param> public DefaultFilesMiddleware([NotNull] RequestDelegate next, [NotNull] IHostingEnvironment hostingEnv, [NotNull] DefaultFilesOptions options) { options.ResolveFileProvider(hostingEnv); _next = next; _options = options; _matchUrl = options.RequestPath; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // >Configure public void Configure(IApplicationBuilder app) { // Serve my app-specific default file, if present. DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("mydefault.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); var options = new DefaultFilesOptions(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); }
/// <summary> /// Enables default file mapping with the given options /// </summary> /// <param name="builder"></param> /// <param name="options"></param> /// <returns></returns> public static IBuilder UseDefaultFiles(this IBuilder builder, DefaultFilesOptions options) { if (builder == null) { throw new ArgumentNullException("builder"); } return builder.Use(next => new DefaultFilesMiddleware(next, options).Invoke); }
/// <summary> /// Enables default file serving with the given options /// </summary> /// <param name="builder"></param> /// <param name="options"></param> /// <returns></returns> public static IAppBuilder UseDefaultFiles(this IAppBuilder builder, DefaultFilesOptions options) { if (builder == null) { throw new ArgumentNullException("builder"); } return builder.Use(typeof(DefaultFilesMiddleware), options); }
public void CustomDefaultFileConfiguration(IAppBuilder app) { var options = new DefaultFilesOptions() { DefaultFileNames = new string[] { "TextFile1.txt" }, FileSystem = new PhysicalFileSystem(@"RequirementFiles\Dir1") }; app.UseDefaultFiles(options); app.UseStaticFiles(new StaticFileOptions() { FileSystem = new PhysicalFileSystem(@"RequirementFiles\Dir1") }); }
/// <summary> /// Enables default file mapping with the given options /// </summary> /// <param name="app"></param> /// <param name="options"></param> /// <returns></returns> public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app, DefaultFilesOptions options) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } return app.UseMiddleware<DefaultFilesMiddleware>(options); }
public DefaultFilesMiddleware(AppFunc next, DefaultFilesOptions options) { if (next == null) { throw new ArgumentNullException("next"); } if (options == null) { throw new ArgumentNullException("options"); } _options = options; _matchUrl = options.RequestPath + "/"; _next = next; }
/// <summary> /// Enables default file mapping with the given options /// </summary> /// <param name="app"></param> /// <param name="configureOptions"></param> /// <returns></returns> public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app, Action<DefaultFilesOptions> configureOptions) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (configureOptions == null) { throw new ArgumentNullException(nameof(configureOptions)); } var options = new DefaultFilesOptions(); configureOptions(options); return app.UseMiddleware<DefaultFilesMiddleware>(options); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add(Configuration["defaultHtml"]); app.UseDefaultFiles(defaultFilesOptions); app.UseStaticFiles(); app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); var defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); }
/// <summary> /// Creates a new instance of the DefaultFilesMiddleware. /// </summary> /// <param name="next">The next middleware in the pipeline.</param> /// <param name="options">The configuration options for this middleware.</param> public DefaultFilesMiddleware(RequestDelegate next, DefaultFilesOptions options) { if (next == null) { throw new ArgumentNullException("next"); } if (options == null) { throw new ArgumentNullException("options"); } if (options.FileSystem == null) { options.FileSystem = new PhysicalFileSystem("." + options.RequestPath.Value); } _next = next; _options = options; _matchUrl = options.RequestPath; }
/// <summary> /// Creates a new instance of the DefaultFilesMiddleware. /// </summary> /// <param name="next">The next middleware in the pipeline.</param> /// <param name="options">The configuration options for this middleware.</param> public DefaultFilesMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, DefaultFilesOptions options) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (hostingEnv == null) { throw new ArgumentNullException(nameof(hostingEnv)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } options.ResolveFileProvider(hostingEnv); _next = next; _options = options; _matchUrl = options.RequestPath; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); //app.UseDirectoryBrowser(); loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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(); } app.UseRouting(); DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("foo.html"); app.UseFileServer(); //app.UseEndpoints(endpoints => //{ // endpoints.MapGet("/", async context => // { // await context.Response.WriteAsync("Hello World..."); // }); //}); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("index.html"); //·ÃÎÊHTML ¾²Ì¬Ò³Ãæ app.UseStaticFiles(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. //public void ConfigureServices(IServiceCollection services) //{ // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ContextInitializer seeder) { var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { context.Request.Path = "wwwroot/index.html"; await next(); } }) .UseCors("AllowAll") .UseMvc() .UseDefaultFiles(options) .UseStaticFiles(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } seeder.Seed().Wait(); //app.UseHttpsRedirection(); //app.UseMvc(); }
// 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(); } app.UseHttpsRedirection(); DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); app.UseStaticFiles(); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); // Middleware to handle all request app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { Console.WriteLine("Content Not Found"); context.Request.Path = "/index.html"; context.Response.StatusCode = 200; await next(); } }); DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("/index.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); app.UseFileServer(enableDirectoryBrowsing: false); app.UseMvc(); }
/// <summary> /// 启用静态文件 /// </summary> /// <param name="app"></param> public static void UseStaticFilesMiddle(this IApplicationBuilder app) { //启动静态文件 根目录 wwwroot //DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); // defaultFilesOptions.DefaultFileNames.Clear(); //defaultFilesOptions.DefaultFileNames.Add("index.html"); // app.UseDefaultFiles(defaultFilesOptions); // app.UseDefaultFiles();//默认含index.html // app.UseStaticFiles(); DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(defaultFilesOptions); app.UseStaticFiles(); #region 文件 //上传文件的文件夹 配置文件静态文件 //app.UseHttpsRedirection(); //app.UseStaticFiles(); var filePath = Configs.UploadConfig.Avatar.UploadPath; if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } app.UseStaticFiles(new StaticFileOptions() { RequestPath = new PathString(Configs.UploadConfig.Avatar.RequestPath), //请求地址 FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(filePath) //用于定位资源的文件系统 }); #endregion }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint( $"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } }); DefaultFilesOptions DefaultFile = new DefaultFilesOptions(); DefaultFile.DefaultFileNames.Clear(); DefaultFile.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(DefaultFile); app.UseStaticFiles(); app.UseDefaultFiles(); // app.Run(context => { // return context.Response.WriteAsync("Welcome to the API Home Page!!!"); // }); app.UseMvc(); }
// 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(); } app.UseFileServer(new FileServerOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "AngularApp")), RequestPath = "", }); //app.UseHttpsRedirection(); DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); // catch non existing path (except files, e.g. ".../dashboard.png" - this still gets the error 404) endpoints.MapFallbackToFile("/index.html"); // ... and catch file errors too endpoints.MapFallbackToFile("{*path:file}", "/index.html"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("home.html"); app.UseDefaultFiles(); app.UseStaticFiles(); /* if (env.IsDevelopment()) * { * app.UseDeveloperExceptionPage(); * } * * app.UseRouting(); * * app.UseEndpoints(endpoints => * { * endpoints.MapGet("/", async context => * { * await context.Response.WriteAsync("Hello World!"); * }); * });*/ }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/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(); } // 设置默认启动页为引导页面 DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("FH.Host.APP.GuidPage/GuidPageIndex.html"); app.UseDefaultFiles(defaultFilesOptions); app.UseHttpsRedirection(); // 强制把HTTP请求转换HTTPS app.UseStaticFiles(); // 配置静态文件中间件,可访问位于 Web 根目录之外的文件 app.UseCookiePolicy(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("demos.html"); app.UseDefaultFiles(options); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store"; context.Context.Response.Headers["Pragma"] = "no-cache"; context.Context.Response.Headers["Expires"] = "-1"; } }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); DefaultFilesOptions options = new DefaultFilesOptions() { RequestPath = "", FileProvider = fileProvider, DefaultFileNames = new List <string> { "index.html" }, }; options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("/index.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { RequestPath = "", FileProvider = fileProvider, }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); //app.UseSwagger(); //app.UseSwaggerUI(c => //{ // c.SwaggerEndpoint("/swagger/v1/swagger.json", "To Do List API V1"); //}); DefaultFilesOptions DefaultFile = new DefaultFilesOptions(); DefaultFile.DefaultFileNames.Clear(); DefaultFile.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(DefaultFile); app.UseStaticFiles(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("websocket-api.html"); ITextWebSocketSubprotocol textWebSocketSubprotocol = new PlainTextWebSocketSubprotocol(); WebSocketConnectionsOptions webSocketConnectionsOptions = new WebSocketConnectionsOptions { AllowedOrigins = new HashSet <string> { "http://localhost:63290" }, SupportedSubProtocols = new List <ITextWebSocketSubprotocol> { new JsonWebSocketSubprotocol(), textWebSocketSubprotocol }, DefaultSubProtocol = textWebSocketSubprotocol, SendSegmentSize = 4 * 1024 }; app.UseDefaultFiles(defaultFilesOptions) .UseStaticFiles() .UseWebSocketsCompression() .MapWebSocketConnections("/socket", webSocketConnectionsOptions) .Run(async(context) => { await context.Response.WriteAsync("-- Demo.AspNetCore.WebSocket --"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("/htmlpage.html"); //将index.html改为需要默认起始页的文件名. app.UseDefaultFiles(options); app.UseStaticFiles(); //app.UseHttpsRedirection(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "/htmlpage.html"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); } DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("app.html"); app.UseDefaultFiles(options); if (env.IsDevelopment()) { app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store"; context.Context.Response.Headers["Pragma"] = "no-cache"; context.Context.Response.Headers["Expires"] = "-1"; } }); } else { app.UseStaticFiles(); } //Cors app.UseCors("AllowAll"); app.UseMvcWithDefaultRoute(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } var swaggerOptions = new Options.SwaggerOptions(); Configuration.GetSection(nameof(Options.SwaggerOptions)).Bind(swaggerOptions); app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; }); app.UseSwaggerUI(option => { option.SwaggerEndpoint(swaggerOptions.UIEndPoint, swaggerOptions.Description); }); DefaultFilesOptions filesOptions = new DefaultFilesOptions(); filesOptions.DefaultFileNames.Clear(); filesOptions.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(filesOptions); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseHttpsRedirection(); app.UseMvc(); }
public void Configuration(IAppBuilder builder) { var rootDirectory = Environment.CurrentDirectory; var loginDirectory = Path.Combine(rootDirectory, "login"); var fs = new PhysicalFileSystem(rootDirectory); var loginFs = new PhysicalFileSystem(loginDirectory); var dfo = new DefaultFilesOptions(); dfo.DefaultFileNames.Add("index.html"); dfo.FileSystem = fs; var sfo = new StaticFileOptions { FileSystem = fs }; var loginSfo = new StaticFileOptions { FileSystem = loginFs }; builder.SetDataProtectionProvider(new DpapiDataProtectionProvider()); var formsAuthenticationProvider = new FormsAuthenticationProvider(); formsAuthenticationProvider.OnValidateLogin = context => { Console.WriteLine("Validating Login"); Console.WriteLine("================"); Console.WriteLine(" Context.AuthType: " + context.AuthenticationType); Console.WriteLine(" Context.Identity: " + (context.Identity != null ? context.Identity.Name : "Not set")); Console.WriteLine(" Context.Environment:"); var response = new OwinResponse(context.Environment); if (LoginContext.GetIsLoginRequest(context.Environment)) { // Need to retrieve username and password from environment b/c it doesn't // come through in the context (even though the context constructor accepts them) var username = context.Environment["formsauthn.username"].ToString(); var password = context.Environment["formsauthn.password"].ToString(); var remember = bool.Parse(context.Environment["formsauthn.remember"].ToString()); Console.WriteLine(" Request.Username: "******" Request.Password: "******" Request.Remember: " + remember); if (username == password) { var identity = new ClaimsIdentity( new GenericIdentity(username, context.AuthenticationType), new[] { new Claim(ClaimTypes.IsPersistent, remember.ToString()) } ); // I assumed that this would take care of populating the cookie for me... but not so much. context.Signin(identity); var msg = "Access granted."; Console.WriteLine(msg); var msgBytes = Encoding.UTF8.GetBytes(msg); return response.Body.WriteAsync(msgBytes, 0, msgBytes.Length); } else { var msg = "Access denied. Try with username=password"; Console.WriteLine(msg); var msgBytes = Encoding.UTF8.GetBytes(msg); return response.Body.WriteAsync(msgBytes, 0, msgBytes.Length); } } else { foreach (var item in context.Environment) { Console.WriteLine(" {0}={1}", item.Key, item.Value != null ? (item.Value is string ? (string) item.Value : item.Value.GetType().FullName) : "Not set" ); } } return response.Body.WriteAsync(new byte[] { }, 0, 0); }; builder.UseFormsAuthentication( new FormsAuthenticationOptions { CookieHttpOnly = true, CookieName = "AuthCookie", CookiePath = "/", CookieSecure = false, LoginPath = "/login/", ExpireTimeSpan = TimeSpan.FromHours(1), ReturnUrlParameter = "returnUrl", SlidingExpiration = true, Provider = formsAuthenticationProvider } ); builder.UseApplicationSignInCookie(); builder.UseDefaultFiles(dfo); builder.UseErrorPage(); builder.MapPath("/login", loginBuilder => loginBuilder.UseProcessLoginPostback(formsAuthenticationProvider).UseStaticFiles(loginSfo)); builder.UseDenyAnonymous().UseStaticFiles(sfo); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISettingsManager settingsManager, IPluginManager pluginManager, IErrorLogRepository errorLogRepository, IOptions <SenparcSetting> senparcSetting) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandler(a => a.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>(); var exception = exceptionHandlerPathFeature.Error; string result; if (env.IsDevelopment()) { result = TranslateUtils.JsonSerialize(new { exception.Message, exception.StackTrace, AddDate = DateTime.Now }); } else { result = TranslateUtils.JsonSerialize(new { exception.Message, AddDate = DateTime.Now }); } context.Response.ContentType = "application/json"; await context.Response.WriteAsync(result); })); app.UseCors(CorsPolicy); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); //app.UseHttpsRedirection(); var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); //if (settingsManager.Containerized) //{ // app.Map($"/{DirectoryUtils.SiteFiles.DirectoryName}/assets", assets => // { // assets.UseStaticFiles(new StaticFileOptions // { // FileProvider = new PhysicalFileProvider(PathUtils.Combine(settingsManager.ContentRootPath, "assets")) // }); // }); //} app.UseStaticFiles(); var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("zh-CN") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("zh-CN"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UsePluginsAsync(settingsManager, pluginManager, errorLogRepository).GetAwaiter().GetResult(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/healthz"); endpoints.MapControllers(); endpoints.MapRazorPages(); }); //api.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller}/{action}/{id?}"); }); app.UseRequestLocalization(); RegisterService.Start(senparcSetting.Value) //自动扫描自定义扩展缓存(二选一) .UseSenparcGlobal(true) //指定自定义扩展缓存(二选一) //.UseSenparcGlobal(false, () => GetExCacheStrategies(senparcSetting.Value)) ; app.UseOpenApi(); app.UseSwaggerUi3(); app.UseReDoc(settings => { settings.Path = "/api/docs"; settings.DocumentPath = "/swagger/v1/swagger.json"; }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(defaultFilesOptions); app.UseStaticFiles(); if (env.IsDevelopment()) { //开启验证异常显示 //PII is hidden 异常处理 IdentityModelEventSource.ShowPII = true; } app.UseCustomExceptionHandler(); app.UseRealIp(x => { //new string[] { "X-Real-IP", "X-Forwarded-For" } x.HeaderKeys = new string[] { "X-Forwarded-For", "X-Real-IP" }; }); app.UseCors(_serviceInfo.CorsPolicy); app.UseSwagger(c => { c.RouteTemplate = $"/{_serviceInfo.ShortName}/swagger/{{documentName}}/swagger.json"; c.PreSerializeFilters.Add((swaggerDoc, httpReq) => { swaggerDoc.Servers = new List <OpenApiServer> { new OpenApiServer { Url = $"/", Description = _serviceInfo.Description } }; }); }); app.UseSwaggerUI(c => { c.SwaggerEndpoint($"/{_serviceInfo.ShortName}/swagger/{_serviceInfo.Version}/swagger.json", $"{_serviceInfo.FullName}-{_serviceInfo.Version}"); c.RoutePrefix = $"{_serviceInfo.ShortName}"; }); app.UseHealthChecks($"/{_srvRegistration.GetConsulConfig().HealthCheckUrl}", new HealthCheckOptions() { Predicate = _ => true, // 该响应输出是一个json,包含所有检查项的详细检查结果 ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); app.UseRouting(); app.UseAuthentication(); app.UseSSOAuthentication(_srvRegistration.IsSSOAuthentication); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireAuthorization(); }); if (env.IsProduction() || env.IsStaging()) { var consulOption = _srvRegistration.GetConsulConfig(); //注册Cap节点到consul var consulAdderss = new Uri(consulOption.ConsulUrl); var discoverOptions = serviceProvider.GetService <DiscoveryOptions>(); var currenServerAddress = app.GetServiceAddress(consulOption); discoverOptions.DiscoveryServerHostName = consulAdderss.Host; discoverOptions.DiscoveryServerPort = consulAdderss.Port; discoverOptions.CurrentNodeHostName = currenServerAddress.Host; discoverOptions.CurrentNodePort = currenServerAddress.Port; discoverOptions.NodeId = currenServerAddress.Host.Replace(".", string.Empty) + currenServerAddress.Port; discoverOptions.NodeName = _serviceInfo.FullName.Replace("webapi", "cap"); discoverOptions.MatchPath = $"/{_serviceInfo.ShortName}/cap"; //注册本服务到consul app.RegisterToConsul(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); m_logger = loggerFactory.CreateLogger <Startup>(); DefaultFilesOptions options = new DefaultFilesOptions(); //options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); app.UseDefaultFiles(new DefaultFilesOptions() { FileProvider = new PhysicalFileProvider( BlogLocationUtil.GetBlogFilesLocation(env)), RequestPath = new PathString("/blog") }); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( BlogLocationUtil.GetBlogFilesLocation(env)), RequestPath = "/blog", OnPrepareResponse = ctx => { // Requires the following import: // using Microsoft.AspNetCore.Http; ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600"); }, } ); //app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { m_logger.LogInformation("Running in development mode"); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { m_logger.LogInformation("Running in production mode"); app.UseExceptionHandler("/Home/Error"); } //app.UseStatusCodePagesWithRedirects("~/errors/code/{0}"); app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder() .AddDefaultSecurePolicy() ); //app.UseApplicationInsightsExceptionTelemetry(); app.UseAuthentication(); //AddExternalAuthentication(app); app.UseMvc(routes => { routes.MapRoute( name: "showTest", template: "{controller=Benchmarks}/{action=Show}/{id}/{version}/{name?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseDeveloperExceptionPage(); } app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .WithExposedHeaders("x-token-expired", "content-disposition")); DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add(Configuration["AppSettings:FrontAppIndexFile"]); app.UseDefaultFiles(defaultFilesOptions); app.UseStaticFiles(); app.UseAuthentication(); app.UseMiddleware(typeof(ExceptionHandleMiddleware)); //loggerFactory.AddAzureWebAppDiagnostics(); app.UseSwagger(); app.UseSwaggerUI( options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint( $"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } }); app.UseSwaggerToPostman(); //var hangfireSection = Configuration.GetSection("Hangfire"); //app.UseHangfireDashboard("/hangfire", new DashboardOptions //{ // IsReadOnlyFunc = (DashboardContext context) => bool.Parse(hangfireSection["Readonly"]) //}); //app.UseHangfireServer(); //app.UseIpRateLimiting(); app.UseMvc(routes => { routes.MapRoute( "default", "{controller=Home}/{action=Index}/{id?}"); }); app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api") && !x.Request.Path.Value.StartsWith("/public"), builder => { builder.UseMvc(routes => { routes.MapSpaFallbackRoute( "spa-fallback", new { controller = "Home", action = "Index" }); }); }); InitializeDatabase(app); //InitializeJobs(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // log.AddConsole(); // log.MinimumLevel = LogLevel.Verbose; // var factory = new LoggerFactory(); /* _logger = log.CreateLogger<Program>(); var loggingConfiguration = new ConfigurationBuilder().AddJsonFile("logging.json").Build(); log.AddConsole(loggingConfiguration); loggingConfiguration.Reload();*/ /* var settings = new ConsoleLoggerSettings() { IncludeScopes = true, Switches = { ["Default"] = LogLevel.Verbose, ["Microsoft"] = LogLevel.Information, } }; factory.AddConsole(settings);*/ // How to manually wire up file-watching without a configuration file // // //factory.AddConsole(new RandomReloadingConsoleSettings()); System.Diagnostics.Trace.Listeners.Add(new DefaultTraceListener()); System.Diagnostics.Trace.AutoFlush = true; app.UseIISPlatformHandler(); // _logger.LogInformation("Starting TEST"); // _logger.LogError("This is a test stephane"); System.Diagnostics.Trace.TraceError("Test Test Test Test"); Debug.WriteLine("TEST TEST TEST"); DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); // _logger.LogDebug("This is a test of the log"); /* app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); });*/ app.Map("/arma", (myAppPath) => this.ConfigureMyAppPath(myAppPath, env)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, ILogger <Startup> logger, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html lang=\"en\"><body>\r\n"); await context.Response.WriteAsync("ERROR!<br><br>\r\n"); var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>(); if (exceptionHandlerPathFeature?.Error is FileNotFoundException) { await context.Response.WriteAsync("File error thrown!<br><br>\r\n"); } await context.Response.WriteAsync("<a href=\"/\">Home</a><br>\r\n"); await context.Response.WriteAsync("</body></html>\r\n"); await context.Response.WriteAsync(new string(' ', 512)); // IE padding }); }); app.UseHsts(); } int count = 0; app.Use(next => async context => { using (new MyStopwatch(logger, $"Time {++count}")) { await next(context); } }); // Default registration. loggerFactory.AddProvider(new ColorConsoleLoggerProvider( new ColorConsoleLoggerConfiguration { LogLevel = LogLevel.Error, Color = ConsoleColor.Red })); // Custom registration with default values. loggerFactory.AddColorConsoleLogger(); // Custom registration with a new configuration instance. loggerFactory.AddColorConsoleLogger(new ColorConsoleLoggerConfiguration { LogLevel = LogLevel.Debug, Color = ConsoleColor.Gray }); // Custom registration with a configuration object. loggerFactory.AddColorConsoleLogger(c => { c.LogLevel = LogLevel.Information; c.Color = ConsoleColor.Blue; }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } logger.LogInformation("test logger"); app.Use(async(context, next) => { Console.WriteLine($"This is a middlerware"); await next.Invoke(); }); // branch // app.Map("/swagger", HandRequestDel); app.MapWhen(context => context.Request.Headers.ContainsKey("Query"), HandRequestDel); //app.Run(async context => //{ // await context.Response.WriteAsync($"This is terminal middlerware"); //}); // cors app.UseCors(); app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseSwagger(); app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/v1/swagger.json", "to do api"); //option.InjectStylesheet("/swagger-ui/custom.css"); }); app.UseRouting(); var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("mydefault.html"); app.UseDefaultFiles(options); // Set up custom content types - associating file extension to MIME type var provider = new FileExtensionContentTypeProvider(); // Add new mappings provider.Mappings[".myapp"] = "application/x-msdownload"; provider.Mappings[".htm3"] = "text/html"; provider.Mappings[".image"] = "image/png"; // Replace an existing mapping provider.Mappings[".rtf"] = "application/x-msdownload"; // Remove MP4 videos. provider.Mappings.Remove(".mp4"); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "MyStaticFiles")), RequestPath = "/staticfiles", OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={6000}"); }, ContentTypeProvider = provider }); app.UseMiddleware <ProductsLinkMiddleware>(); app.Use(next => async context => { using (new MyStopwatch(logger, $"Time {++count}")) { await next(context); } }); app.UseAuthentication(); app.UseAuthorization(); app.Use(next => async context => { using (new MyStopwatch(logger, $"Time {++count}")) { await next(context); } }); // query endpoints app.Use(next => httpContext => { var endPoints = httpContext.GetEndpoint(); if (endPoints is null) { return(Task.CompletedTask); } Console.WriteLine($"Endpoints:{endPoints.DisplayName}"); if (endPoints is RouteEndpoint routeEndpoint) { Console.WriteLine($"Endpoint has route pattern:" + routeEndpoint.RoutePattern.RawText); } foreach (var metadata in endPoints.Metadata) { Console.WriteLine($"Endpoint has metadata: {metadata}"); } return(next(httpContext)); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapGet("/hello/{name:alpha}", async context => { var name = context.Request.RouteValues["name"]; await context.Response.WriteAsync($"hello{name}"); }); // Configure the Health Check endpoint and require an authorized user. endpoints.MapHealthChecks("/healthz"); }); app.UseEndpoints(endpoints => { endpoints.MapGet("/hello/{name:alpha}", async context => { var name = context.Request.RouteValues["name"]; await context.Response.WriteAsync($"hello{name}"); }); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); //обработка необрабоанных исключений app.UseExceptionHandler(errorApp => { //пишем в ответ код 500 //и информацию об исключении в формате json errorApp.Run(async context => { context.Response.StatusCode = 500; // or another Status accordingly to Exception Type context.Response.ContentType = "application/json"; var error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { var ex = error.Error; await context.Response.WriteAsync(new ErrorDto() { Code = ex.GetType().Name, Message = ex.Message }.ToString(), Encoding.UTF8); } }); }); //"аутентификация" на основе cookie app.Use((context, next) => { //берем куку user_id и считаем её иднтификатором пользователя //если такой куки нет, генерируем новуй гуид и запихиваем в эту куку в ответ var cookies = context.Request.Cookies; var userIdCookieName = "user_id"; string userId; if (!cookies.TryGetValue(userIdCookieName, out userId)) { userId = Guid.NewGuid().ToString(); } context.Response.Cookies.Append(userIdCookieName, userId, new CookieOptions() { Expires = DateTimeOffset.MaxValue }); List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Name, userId) }; ClaimsIdentity identity = new ClaimsIdentity(claims, "Cookie"); ClaimsPrincipal principal = new ClaimsPrincipal(identity); context.User = principal; return(next.Invoke()); }); //подключение статических файлов и настройка страницы по умолчанию DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("app/index.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); app.UseMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { //app.UseExceptionHandler("/Home/Error"); //default Exception Handling //Custom Exception Handling app.UseExceptionHandler((builder) => { builder.Run(async(context) => { context.Response.StatusCode = 500; context.Response.Headers["Content-Type"] = "text/html"; await context.Response.WriteAsync("<h2>Some Error Ocuured</h2>"); var exceptionPathFearture = context.Features.Get <IExceptionHandlerPathFeature>(); await context.Response.WriteAsync($"<p>{exceptionPathFearture.Error.Message}</p>"); }); }); app.UseHsts(); } app.UseStatusCodePages("text/html", "Client side error occured with status code {0}"); //used for Status code messages app.UseStatusCodePagesWithRedirects("/index.html"); app.UseStatusCodePagesWithReExecute("/index.html"); app.UseHttpsRedirection(); var options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("index.html"); options.DefaultFileNames.Add("default.html"); //app.UseDefaultFiles(options); //app.UseStaticFiles(new StaticFileOptions //{ // RequestPath = "/docs", // FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "mydocs")) //}); app.UseStaticFiles(); //configured to serve static files from wwwroot //app.UseDirectoryBrowser(new DirectoryBrowserOptions //{ // RequestPath = "/docs", // FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "mydocs")) //}); var fileOptions = new FileServerOptions { RequestPath = "/docs", FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "mydocs")), EnableDirectoryBrowsing = true }; fileOptions.DefaultFilesOptions.DefaultFileNames.Clear(); fileOptions.DefaultFilesOptions.DefaultFileNames.Add("index.html"); app.UseFileServer(fileOptions); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
// 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(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/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(); //FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider(); //provider.Mappings[".image"] = "image/png"; //provider.Mappings.Remove(".mp4"); //app.UseStaticFiles(new StaticFileOptions //{ // FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")), // //RequestPath = new PathString("/imgs"), // //ContentTypeProvider = provider, // ContentTypeProvider = new MyContentTypeProvider(), // DefaultContentType = "image/png", // HttpsCompression = HttpsCompressionMode.Compress, // ServeUnknownFileTypes = true, // OnPrepareResponse = (response) => // { // response.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age=31536000"; // response.Context.Response.Headers[HeaderNames.Pragma] = $"public,max-age=31536000"; // response.Context.Response.Headers[HeaderNames.Expires] = DateTime.UtcNow.AddYears(1).ToString("R"); // if (response.Context.Request.Path.StartsWithSegments("/imgs")) // { // if (response.Context.User.Identity.IsAuthenticated) // { // if (response.Context.User.IsInRole("Admin")) // { // return; // } // else // { // response.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; // throw new UnauthorizedAccessException(); // } // } // else // { // response.Context.Response.Redirect("/Identity/Account/Login"); // } // } // } //}); //UseDefaultFiles must be called before UseStaticFiles to serve the default file. //default.htm default.html index.htm index.html // Serve my app-specific default file, if present. DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("mydefault.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); // For the wwwroot folder //app.UseStaticFiles(new StaticFileOptions //{ // FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")), // RequestPath = "/StaticFiles" //}); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")), RequestPath = "/MyImages" }); app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")), RequestPath = "/MyImages" }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <SenparcSetting> senparcSetting, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region 读取静态文件 app.UseStaticFiles(); //app.UseStaticFiles(new StaticFileOptions //{ // FileProvider = new PhysicalFileProvider( // Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")), // RequestPath = "/StaticFiles" //}); #endregion 读取静态文件 app.UseCookiePolicy(); //使用缓存 app.UseResponseCaching(); //注册Session服务 app.UseSession(); #region 使用跨域 app.UseCors("Cors"); #endregion 使用跨域 #region 使用swagger //使用swagger app.UseSwagger(); //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); //option.SwaggerEndpoint("/swagger/v2/swagger.json", "API V1"); option.RoutePrefix = "swagger"; option.DocumentTitle = "sparktodo API"; }); #endregion 使用swagger #region 使用Ids服务 app.UseIdentityServer(); #endregion 使用Ids服务 //使用https app.UseHttpsRedirection(); //默认网站打开跳转静态地址 if (!string.IsNullOrEmpty(Appsettings.GetSectionValue("AppSettings:DefaultHtml"))) { DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add(Appsettings.GetSectionValue("AppSettings:DefaultHtml")); app.UseDefaultFiles(defaultFilesOptions); } app.UseStaticFiles(); app.UseRouting(); //app.UseMvc(); #region Senparc.Weixin SDK // 启动 CO2NET 全局注册,必须! 关于 UseSenparcGlobal() 的更多用法见 CO2NET Demo:https://github.com/Senparc/Senparc.CO2NET/blob/master/Sample/Senparc.CO2NET.Sample.netcore3/Startup.cs var registerService = app.UseSenparcGlobal(env, senparcSetting.Value, globalRegister => { #region CO2NET 全局配置 #region APM 系统运行状态统计记录配置 //测试APM缓存过期时间(默认情况下可以不用设置) Senparc.CO2NET.APM.Config.EnableAPM = true;//默认已经为开启,如果需要关闭,则设置为 false Senparc.CO2NET.APM.Config.DataExpire = TimeSpan.FromMinutes(60); #endregion APM 系统运行状态统计记录配置 #endregion CO2NET 全局配置 }, true) //使用 Senparc.Weixin SDK .UseSenparcWeixin(senparcWeixinSetting.Value, weixinRegister => { #region 微信相关配置 /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ #region 注册公众号或小程序(按需) //注册公众号(可注册多个) -- DPBMARK MP weixinRegister .RegisterMpAccount(senparcWeixinSetting.Value, "公众号") // DPBMARK_END //除此以外,仍然可以在程序任意地方注册公众号或小程序: //AccessTokenContainer.Register(appId, appSecret, name);//命名空间:Senparc.Weixin.MP.Containers #endregion 注册公众号或小程序(按需) #region 注册微信支付(按需) -- DPBMARK TenPay //注册最新微信支付版本(V3)(可注册多个) .RegisterTenpayV3(senparcWeixinSetting.Value, "公众号") //记录到同一个 SenparcWeixinSettingItem 对象中 #endregion 注册微信支付(按需) -- DPBMARK TenPay ; /* 微信配置结束 */ #endregion 微信相关配置 }); AccessTokenContainer.RegisterAsync(senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret); #endregion Senparc.Weixin SDK #region 授权认证ids app.UseAuthentication(); //认证 app.UseAuthorization(); //授权 #endregion 授权认证ids app.UseMiddleware <Middleware.AskMiddleWare>(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //注册socket app.Map("/socket", WebSocketHelper.Map); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("/admin/index.html"); app.UseDefaultFiles(); //启用wwwroot可访问 app.UseStaticFiles(); app.UseCors(MyAllowSpecificOrigins); app.UseSession(); //判断Log目录是否存在,没有则创建 var logPath = Path.Combine(AppContext.BaseDirectory, "log"); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } var fileProvider = new PhysicalFileProvider(logPath); var requestPath = new PathString("/log"); var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".log"] = "application/x-msdownload"; app.UseStaticFiles(new StaticFileOptions() { FileProvider = fileProvider, RequestPath = requestPath, ContentTypeProvider = provider, }); app.UseDirectoryBrowser(new DirectoryBrowserOptions() { FileProvider = fileProvider, RequestPath = requestPath, }); app.UseDirectoryBrowser(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "SecretGarden API"); }); //app.UseHttpsRedirection(); app.UseAuthentication(); //授权 app.UseRouting(); app.UseAuthorization(); //认证 app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // Defines the middleware for the request pipeline public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { #region 对中间件管道进行分支.Map 扩展用作约定来创建管道分支。Map 基于给定请求路径的匹配项来创建请求管道分支。 如果请求路径以给定路径开头,则执行分支。 app.Map("/map1", HandleMapTest1); app.Map("/map2", HandleMapTest2); //Map 支持嵌套 app.Map("/level1", level1App => { level1App.Map("/level2a", level2AApp => { // "/level1/level2a" processing }); level1App.Map("/level2b", level2BApp => { // "/level1/level2b" processing }); }); //Map 还可同时匹配多个段 app.Map("/map1/seg1", HandleMultiSeg); //MapWhen 基于给定谓词的结果创建请求管道分支 app.MapWhen(context => context.Request.Query.ContainsKey("branch"), HandleBranch); #endregion //UseWhen 也基于给定谓词的结果创建请求管道分支。 与 MapWhen 不同的是,如果这个分支不发生短路或包含终端中间件,则会重新加入主管道 app.UseWhen(context => context.Request.Query.ContainsKey("branch"), HandleBranchAndRejoin); #region autofac 解析出对象 this.AutofacContainer = app.ApplicationServices.GetAutofacRoot(); var servicenamed = this.AutofacContainer.Resolve <IMyService>(); servicenamed.ShowCode(); var service = this.AutofacContainer.ResolveNamed <IMyService>("service2"); service.ShowCode(); #region 子容器 using (var myscope = AutofacContainer.BeginLifetimeScope("myscope")) { var service0 = myscope.Resolve <MyNameService>(); using (var scope = myscope.BeginLifetimeScope()) { var service1 = scope.Resolve <MyNameService>(); var service2 = scope.Resolve <MyNameService>(); Console.WriteLine($"service1=service2:{service1 == service2}"); Console.WriteLine($"service1=service0:{service1 == service0}"); } } #endregion #endregion //中间件顺序 //https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1 // 注入中间件 处理HttpContext请求 Console.WriteLine("5 Startup.Configure"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseWebSockets(); //要提供默认文件,必须在 UseStaticFiles 前调用 UseDefaultFiles。 //UseDefaultFiles 实际上用于重写 URL,不提供文件。 //通过 UseStaticFiles 启用静态文件中间件来提供文件。 app.UseDefaultFiles(); //在请求的文件夹中搜索default.htm、 default.html、index.htm、index.html //http://<server_address>/StaticFiles DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("mydefault.html");// 将mydefault.html设置为默认页 app.UseDefaultFiles(options); ////wwwroot // //css // //images // //js ////MyStaticFiles // //images // //banner1.svg app.UseStaticFiles(); // For the wwwroot folder //< img src = "~/images/banner1.svg" alt = "ASP.NET" class="img-responsive" /> //等价于 wwwroot/images/banner1.svg //http://<server_address>/StaticFiles/images/banner1.svg 前端请求的地址 //应用重定向StaticFiles到MyStaticFiles //< img src = "~/StaticFiles/images/banner1.svg" alt = "ASP.NET" class="img-responsive" /> //等价于 MyStaticFiles/images/banner1.svg var cachePeriod = env.IsDevelopment() ? "600" : "604800"; var provider = new FileExtensionContentTypeProvider(); // Add new mappings provider.Mappings[".myapp"] = "application/x-msdownload"; provider.Mappings[".htm3"] = "text/html"; provider.Mappings[".image"] = "image/png"; // Replace an existing mapping provider.Mappings[".rtf"] = "application/x-msdownload"; // Remove MP4 videos. provider.Mappings.Remove(".mp4"); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")), RequestPath = "/StaticFiles", OnPrepareResponse = ctx => { // Requires the following import: // using Microsoft.AspNetCore.Http; ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}"); }, ContentTypeProvider = provider //静态文件授权 //var file = Path.Combine(Directory.GetCurrentDirectory(), // "MyStaticFiles", "images", "banner1.svg"); //return PhysicalFile(file, "image/svg+xml"); }); //启用目录浏览 出于安全考虑默认关闭 //同时需要调用 Startup.ConfigureServices 中的services.AddDirectoryBrowser(); 方法来添加所需服务 app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")), RequestPath = "/MyImages" }); //UseFileServer 结合了 UseStaticFiles、UseDefaultFiles 和 UseDirectoryBrowser(可选)的功能 app.UseFileServer(); //以下代码提供静态文件和默认文件。 未启用目录浏览。 app.UseFileServer(enableDirectoryBrowsing: true); //通过启用目录浏览基于无参数重载进行构建: app.UseFileServer(new FileServerOptions { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")), RequestPath = "/StaticFiles", EnableDirectoryBrowsing = true }); app.UseRouting(); // app.UseRequestLocalization(); // app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); // app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //Run 委托不会收到 next 参数。 第一个 Run 委托始终为终端,用于终止管道。 //Run 是一种约定。 某些中间件组件可能会公开在管道末尾运行的 Run[Middleware] 方法 //用 Use 将多个请求委托链接在一起。 next 参数表示管道中的下一个委托。 可通过不 调用 next 参数使管道短路。 app.Use(async(context, next) => { // Do work that doesn't write to the Response. await next.Invoke(); // Do logging or other work that doesn't write to the Response. }); app.Run(async context => { await context.Response.WriteAsync("Hello, World!"); }); }
/// <summary> /// 启用WebHost /// </summary> /// <param name="app"></param> /// <param name="hostOptions"></param> /// <param name="env"></param> /// <returns></returns> public static IApplicationBuilder UseWebHost(this IApplicationBuilder app, HostOptions hostOptions, IHostEnvironment env) { //异常处理 app.UseExceptionHandle(); //设置默认文档 var defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(defaultFilesOptions); //基地址 var pathBase = hostOptions.PathBase; if (pathBase.NotNull()) { pathBase = pathBase.Trim(); if (!pathBase.StartsWith('/')) { pathBase = $"/{pathBase}"; } //1、配置请求基地址: app.Use((context, next) => { context.Request.PathBase = pathBase; return(next()); }); // 2、配置静态文件基地址: app.UsePathBase(pathBase); } app.UseDefaultPage(); app.UseDocs(); //反向代理 if (hostOptions.Proxy) { app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); } //路由 app.UseRouting(); //CORS app.UseCors("Default"); //认证 app.UseAuthentication(); //授权 app.UseAuthorization(); //配置端点 app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); //开启Swagger if (hostOptions.Swagger || env.IsDevelopment()) { app.UseCustomSwagger(); } //加载模块 app.UseModules(env); return(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyContext myContext, ITasksQzSvc tasksQzSvc, ISchedulerCenter schedulerCenter, IHostApplicationLifetime lifetime) { // Ip限流,尽量放管道外层 app.UseIpLimitMildd(); // 记录请求与返回数据 app.UseReuestResponseLog(); // 用户访问记录(必须放到外层,不然如果遇到异常,会报错,因为不能返回流) app.UseRecordAccessLogsMildd(); // signalr app.UseSignalRSendMildd(); // 记录ip请求 app.UseIPLogMildd(); // 查看注入的所有服务 app.UseAllServicesMildd(_services); if (env.IsDevelopment()) { // 在开发环境中,使用异常页面,这样可以暴露错误堆栈信息,所以不要放在生产环境。 app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // 在非开发环境中,使用HTTP严格安全传输(or HSTS) 对于保护web安全是非常重要的。 // 强制实施 HTTPS 在 ASP.NET Core,需要配合 app.UseHttpsRedirection()与services.AddHstsSetup() //app.UseHsts(); // HSTS 中间件(UseHsts)用于向客户端发送 HTTP 严格传输安全协议(HSTS)标头 } // 自定义Swagger权限拦截中间件,放到Swagger中间件之前 app.UseSession(); app.UseSwaggerAuthorized(); // 封装Swagger展示 app.UseSwaggerMildd(() => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Xu.WebApi.index.html")); // ↓↓↓↓↓↓ 注意下边这些中间件的顺序,很重要 ↓↓↓↓↓↓ // CORS跨域 app.UseCors(Appsettings.App(new string[] { "Startup", "Cors", "PolicyName" })); // 重定向中间件,用于将 HTTP 请求重定向到 HTTPS //app.UseHttpsRedirection(); // 使用静态文件 DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions(); defaultFilesOptions.DefaultFileNames.Clear(); defaultFilesOptions.DefaultFileNames.Add("index.html"); app.UseDefaultFiles(defaultFilesOptions); // 默认使用wwwroot静态文件 app.UseStaticFiles(); // 使用cookie app.UseCookiePolicy(); // 返回错误码 app.UseStatusCodePages(); // Routing app.UseRouting(); // 这种自定义授权中间件,可以尝试,但不推荐 // app.UseJwtTokenAuth(); // 先开启认证--验证当前请求的用户,并设置HttpContext.User,当OAuth callbacks时,会中止执行下一个中间件。 app.UseAuthentication(); // 然后是授权中间件 app.UseAuthorization(); // 开启性能分析 app.UseMiniProfilerMildd(); // 开启异常中间件,要放到最后 app.UseExceptionHandlerMidd(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapHub <ChatHub>("/api/chatHub"); }); // 生成种子数据 app.UseSeedDataMildd(myContext, Env.WebRootPath); // 开启QuartzNetJob调度服务 app.UseQuartzJobMildd(tasksQzSvc, schedulerCenter); // 服务注册 app.UseConsulMildd(Configuration, lifetime); // 事件总线,订阅服务 app.ConfigureEventBus(); }