public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { app.UseFileServer(); app.UseSignalR<RawConnection>("/raw-connection"); app.UseSignalR(); }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { app.UseWebSockets(); app.Use((context, next) => { context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "*" }); context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "*" }); return next(); }); app.UseFileServer(); app.UseSignalR<RawConnection>("/raw-connection"); app.UseSignalR(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Setup configuration sources. May be unnecessary var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json").AddEnvironmentVariables(); ; Configuration = builder.Build(); loggerFactory.AddConsole(); serviceHelpers.rootPath = env.ContentRootPath; // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{player?}", defaults: new { controller = "Player", action = "Index" } ); routes.MapRoute( name: "Robot", template: "{controller}/{action}/{bot?}" ); }); app.UseFileServer(); app.UseSignalR(); }
// 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(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSignalR(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); // Add the following to the request pipeline only in development environment. if (env.IsEnvironment("Development")) { app.UseBrowserLink(); } /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. */ app.UseErrorPage(ErrorPageOptions.ShowAll); app.ConfigureSecurity(); //Configure SignalR app.UseSignalR(); // Add MVC to the request pipeline app.ConfigureRoutes(); MyShuttleDataInitializer.InitializeDatabaseAsync(app.ApplicationServices).Wait(); }
public void Configure(IApplicationBuilder app) { /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. */ app.UseErrorPage(ErrorPageOptions.ShowAll); //Configure SignalR app.UseSignalR(); //Serves static files in the application. app.UseFileServer(); //Configure WebFx app.UseMvc(routes => { routes.MapRoute( null, "{controller}/{action}", new { controller = "Home", action = "Index" }); routes.MapRoute( null, "api/{controller}/{action}", new { controller = "Home", action = "Index" }); routes.MapRoute( null, "api/{controller}", new { controller = "Home" }); }); }
public void Configure(IApplicationBuilder app) { app.UseDefaultFiles(); app.UseStaticFiles(); // Add a new middleware validating access tokens. app.UseOAuthValidation(options => { options.Events = new OAuthValidationEvents { // Note: for SignalR connections, the default Authorization header does not work, // because the WebSockets JS API doesn't allow setting custom parameters. // To work around this limitation, the access token is retrieved from the query string. OnRetrieveToken = context => { context.Token = context.Request.Query["access_token"]; return Task.FromResult(0); } }; }); app.UseSignalR<SimpleConnection>("/signalr"); // Add a new middleware issuing access tokens. app.UseOpenIdConnectServer(options => { options.Provider = new AuthenticationProvider(); // Enable the token endpoint. options.TokenEndpointPath = "/connect/token"; options.AllowInsecureHttp = true; }); }
public void Configure(IApplicationBuilder app) { // Setup configuration sources var configuration = new Configuration(); configuration.AddJsonFile("config.json"); configuration.AddEnvironmentVariables(); // Set up application services app.UseServices(services => { // Add EF services to the services container and configure DbContext services.ConfigureDataContext(configuration); // Register MyShuttle dependencies services.ConfigureDependencies(); //Add Identity services to the services container services.AddDefaultIdentity<MyShuttleContext, ApplicationUser, IdentityRole>(configuration); services.ConfigureCookieAuthentication(options => { options.LoginPath = new Microsoft.AspNet.Http.PathString("/Carrier/Login"); }); // Add MVC services to the services container services.AddMvc(); services .AddSignalR(options => { options.Hubs.EnableDetailedErrors = true; }); }); // Enable Browser Link support app.UseBrowserLink(); /* Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. * Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. */ app.UseErrorPage(ErrorPageOptions.ShowAll); // Add static files to the request pipeline app.UseStaticFiles(); app.ConfigureSecurity(); //Configure SignalR app.UseSignalR(); // Add cookie-based authentication to the request pipeline // Add MVC to the request pipeline app.ConfigureRoutes(); MyShuttleDataInitializer.InitializeDatabaseAsync(app.ApplicationServices).Wait(); }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { #if DNX451 string OutputTemplate = "{SourceContext} {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; var serilog = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.RollingFile(@".\SignalR-Log-{Date}.txt", outputTemplate: OutputTemplate); loggerFactory.AddSerilog(serilog); #endif app.UseFileServer(); app.UseSignalR<RawConnection>("/raw-connection"); app.UseSignalR(); }
public void Configure(IApplicationBuilder app) { app.UseSignalR(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); }
public void Configure(IApplicationBuilder app) { app.UseGlimpse(); // TODO: Nedd to find a better way of registering this. Problem is that this // registration is aspnet5 specific. app.UseSignalR("/Glimpse/Data/Stream"); app.UseWelcomePage(); }
public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseSignalR(); app.Run(async (context) => { context.Response.ContentType = "text/html"; await context.Response.SendFileAsync("index.html"); }); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Configure the HTTP request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(); app.UseSignalR(); }
public void Configure(IApplicationBuilder app) { // Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); ////app.UseFacebookAuthentication(); ////app.UseGoogleAuthentication(); ////app.UseTwitterAuthentication(); // The MicrosoftAccount service has restrictions that prevent the use of http://localhost:5001/ for test applications. // As such, here is how to change this sample to uses http://ktesting.com:5001/ instead. // Edit the Project.json file and replace http://localhost:5001/ with http://ktesting.com:5001/. // From an admin command console first enter: // notepad C:\Windows\System32\drivers\etc\hosts // and add this to the file, save, and exit (and reboot?): // 127.0.0.1 ktesting.com // Then you can choose to run the app as admin (see below) or add the following ACL as admin: // netsh http add urlacl url=http://ktesting:5001/ user=[domain\user] // The sample app can then be run via: // k web ////app.UseMicrosoftAccountAuthentication(); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the OpenLan sample data SampleData.InitializeOpenLanDatabaseAsync(app.ApplicationServices).Wait(); }
public void Configure(IApplicationBuilder app) { app.UseMvc(); app.UseFileServer(); app.UseSignalR(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!.\nThis is my first demo. This is a ASP.NET vNext test Application on Docker.\n\nMaintained by Ashish Sharma\nEze Software Group"); }); }
public void Configure(IApplicationBuilder app) { app.UseSignalR(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); }); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Information); var logger = loggerFactory.CreateLogger(typeof(Startup).Name); logger.LogInformation("Starting"); // Add static files to the request pipeline. app.UseStaticFiles(); app.UseSignalR(); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Configure the HTTP request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(); // Add the following route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); app.UseFileServer(); app.UseSignalR("/sgnr"); }
public void Configure(IApplicationBuilder app, IHostingEnvironment environment, ILoggerFactory factory) { factory.AddConsole(); factory.AddDebug(); app.UseIISPlatformHandler(); if (environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); // Add a new middleware validating access tokens. app.UseJwtBearerAuthentication(options => { // Automatic authentication must be enabled // for SignalR to receive the access token. options.AutomaticAuthenticate = true; // Automatically disable the HTTPS requirement for development scenarios. options.RequireHttpsMetadata = !environment.IsDevelopment(); // Note: the audience must correspond to the address of the SignalR server. options.Audience = "http://localhost:5000/"; // Note: the authority must match the address of the identity server. options.Authority = "http://localhost:5000/"; options.Events = new JwtBearerEvents { // Note: for SignalR connections, the default Authorization header does not work, // because the WebSockets JS API doesn't allow setting custom parameters. // To work around this limitation, the access token is retrieved from the query string. OnReceivingToken = context => { // Note: when the token is missing from the query string, // context.Token is null and the JWT bearer middleware will // automatically try to retrieve it from the Authorization header. context.Token = context.Request.Query["access_token"]; return Task.FromResult(0); } }; }); app.UseWebSockets(); app.UseSignalR<SimpleConnection>("/signalr"); // Add a new middleware issuing access tokens. app.UseOpenIdConnectServer(options => { options.Provider = new AuthenticationProvider(); }); }
public void Configure(IApplicationBuilder app) { app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseWebSockets(); app.UseSignalR(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); app.UseWebSockets(); app.UseSignalR(); app.UseDeveloperExceptionPage(); app.UseExceptionHandler("/Home/Error"); }
// 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) { app.UseSignalR(); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859 try { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { serviceScope.ServiceProvider.GetService<ApplicationDbContext>() .Database.Migrate(); } } catch { } } app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.UseIdentity(); // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public async void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Warning; loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseAutoAjax(); app.UseIdentity(); app.UseExceptionHandler("/Shared/Prompt"); app.UseStaticFiles(); app.UseSignalR(); app.UseMvc(x => x.MapRoute("default", "{controller=Home}/{action=Index}/{id?}")); await SampleData.InitDB(app.ApplicationServices); }
// Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app,ILoggerFactory loggerFactory, IHostingEnvironment env,IRuntimeEnvironment runtimeEnv,IConnectionManager connectionManager) { app.UseStaticFiles(); app.UseIISPlatformHandler(); app.UseCors("OpenBookAPI"); app.UseSwagger(); app.UseSwaggerUi(); app.UseSignalR(); var hubContext = connectionManager.GetHubContext<OpenBookAPI.SignalR.Hubs.LogHub>(); app.UseJwtBearerAuthentication(options => { options.Audience = Configuration["Auth:ClientId"]; options.Authority = Configuration["Auth:Domain"]; options.AuthenticationScheme = "Automatic"; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateLifetime = true }; }); var localLogger = new LoggerConfiguration() .WriteTo.Trace() .WriteTo.Console().CreateLogger(); var signalRlogger = new LoggerConfiguration() .WriteTo.Sink(new SignalRSink(hubContext, 10)) .MinimumLevel.Warning() .CreateLogger(); var azureLogger = new LoggerConfiguration() .WriteTo.AzureDocumentDB(new System.Uri("https://openbook.documents.azure.com:443/"), "j4Hzifc5HL6z4uNt152t6ECrI5J7peGpSJDlwfkEzn5Vs94pAxf71N3sw3iQS6YneXC0CvxA+MdQjP/GKVbo6A==") .MinimumLevel.Warning() .CreateLogger(); if (runtimeEnv.OperatingSystem.Equals("Windows", StringComparison.OrdinalIgnoreCase)) { loggerFactory.AddSerilog(azureLogger); } if (env.IsDevelopment()) { loggerFactory.AddSerilog(localLogger); } loggerFactory.AddSerilog(signalRlogger); //should go at the end app.UseMvc(); }
public void Configure(IApplicationBuilder app, IConnectionManager connectionManager, IDivineLogger<SqlDataStore> logger) { app.UseStaticFiles(); app.UseCors("AllowAll"); app.UseWebSockets(); app.Map("/DivineSocket", a => a.UseDivineSocket()); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSignalR(); ServiceBusReceiver(connectionManager, logger); }/// <summary>
public void Configure(IApplicationBuilder app) { app.UseServices(services => { services.AddSignalR(options => { options.Hubs.EnableDetailedErrors = true; // options.Hubs.RequireAuthentication(); }); }); //app.UseFileServer(); //app.UseSignalR<RawConnection>("/raw-connection"); app.UseSignalR(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors(config => config.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseWebSockets(); app.UseSignalR("/signalr"); app.UseMvc(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) { app.ApplicationServices .GetService<Db>() .Database .EnsureCreated(); loggerfactory.AddConsole(); app.UseErrorHandler("/Home/Error"); app.UseStaticFiles(); app.UseSignalR(); app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseIISPlatformHandler(); app.UseExceptionHandler("/Home/Error"); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSignalR(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, RoleManager <IdentityRole> roleManager, UserManager <MyUser> userManager, ITicketService _ticketService) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); app.UseStaticFiles(); #region Swagger app.UseSwaggerUi3WithApiExplorer(settings => { settings.GeneratorSettings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase; settings.GeneratorSettings.Title = "VAS API"; settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("Bearer")); settings.GeneratorSettings.DocumentProcessors.Add(new SecurityDefinitionAppender("Bearer", new SwaggerSecurityScheme { Type = SwaggerSecuritySchemeType.ApiKey, Name = "Authorization", Description = "Copy 'Bearer ' + valid JWT token into field", In = SwaggerSecurityApiKeyLocation.Header })); }); #endregion #region Identity var task = RolesExtenstions.InitAsync(roleManager, userManager); task.Wait(); #endregion #region MapsterMapper MapsterConfig map = new MapsterConfig(); map.Run(); #endregion #region Hangfire app.UseHangfireDashboard(); app.UseHangfireServer(); TestBackgroud background = new TestBackgroud(_ticketService); //BackgroundJob.Enqueue(() => background.ChangStatusOnTicket()); RecurringJob.AddOrUpdate(() => background.ChangeStatusOnTicket(), "0,30 7-23 * * *"); #endregion app.UseCors("AllowAll"); app.UseHttpsRedirection(); #region SignalR app.UseSignalR(r => { r.MapHub <CenterHub>("/centerHub"); }); #endregion 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(); // Webpack initialization with hot-reload. app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, }); } 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.UseRewriter(new RewriteOptions() .AddRedirectToWww() .AddRedirectToHttps() ); app.UseSignalR(routes => { routes.MapHub <UpdateHub>("/updatehub"); }); // If not requesting /api*, rewrite to / so SPA app will be returned app.UseSpaFallback(new SpaFallbackOptions() { ApiPathPrefix = "/api", RewritePath = "/" }); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { IHeaderDictionary headers = context.Context.Response.Headers; string contentType = headers["Content-Type"]; if (contentType == "application/x-gzip") { if (context.File.Name.EndsWith("js.gz")) { contentType = "application/javascript"; } else if (context.File.Name.EndsWith("css.gz")) { contentType = "text/css"; } headers.Add("Content-Encoding", "gzip"); headers["Content-Type"] = contentType; } } }); 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, IHostingEnvironment env, IServiceProvider serviceProvider) { //ServiceProvider = serviceProvider; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors( builder => builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials()) .UseStaticFiles() .UseWebSockets(); app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api/")) { context.Request.Path = "/index.html"; await next(); } }); app.UseMvcWithDefaultRoute(); app.UseDefaultFiles(); app.UseStaticFiles() .UseSwaggerUi(); Log.Debug(@"initializing Database..."); EnsureMigrationOfContext <SettingsContext>(serviceProvider); EnsureMigrationOfContext <ExtractsContext>(serviceProvider); app.UseSignalR( routes => { routes.MapHub <ExtractActivity>($"/{nameof(ExtractActivity).ToLower()}"); routes.MapHub <CbsActivity>($"/{nameof(CbsActivity).ToLower()}"); routes.MapHub <DwhSendActivity>($"/{nameof(DwhSendActivity).ToLower()}"); routes.MapHub <CbsSendActivity>($"/{nameof(CbsSendActivity).ToLower()}"); } ); Mapper.Initialize(cfg => { cfg.AddDataReaderMapping(); cfg.AddProfile <TempExtractProfile>(); cfg.AddProfile <TempMasterPatientIndexProfile>(); } ); DomainEvents.Init(); try { DapperPlusManager.AddLicense("1755;701-ThePalladiumGroup", "9005d618-3965-8877-97a5-7a27cbb21c8f"); if (!Z.Dapper.Plus.DapperPlusManager.ValidateLicense(out var licenseErrorMessage)) { throw new Exception(licenseErrorMessage); } } catch (Exception e) { Log.Debug($"{e}"); throw; } Log.Debug(@"initializing Database [Complete]"); Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug (@" _____ _ | __ \ (_) | | | |_ ____ _ _ __ _ | | | \ \ /\ / / _` | '_ \| | | |__| |\ V V / (_| | |_) | | |_____/ \_/\_/ \__,_| .__/|_| | | |_| "); Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug("Dwapi started !"); }
public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IConnectionManager connectionManager, IServiceProvider serviceProvider ) { //Set up dot instead of comma in float values System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); customCulture.NumberFormat.NumberDecimalSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = customCulture; //debug settings bool webServerDebug = false; bool webServerEnable = false; try { webServerDebug = Boolean.Parse(Configuration["WebServer:Debug"]); webServerEnable = Boolean.Parse(Configuration["WebServer:Enable"]); } catch { Console.WriteLine("Bad configuration in appsettings.json file."); return; } if (webServerDebug) { loggerFactory.AddConsole(LogLevel.Debug); } else { loggerFactory.AddConsole(LogLevel.Error); } loggerFactory.AddDebug(); //web server settings if (webServerEnable) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseRuntimeInfoPage("/info"); app.UseWebSockets(); app.UseSignalR(); app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); app.UseStaticFiles(); app.UseStatusCodePages(); //redirect to /FirstRun app.Use(async(context, next) => { if (Boolean.Parse(Configuration["FirstRun"]) && !context.Request.Path.ToUriComponent().StartsWith("/FirstRun")) { context.Response.Redirect("/FirstRun"); return; } //invoke next component await next.Invoke(); }); app.UseCookieAuthentication(options => { options.AuthenticationScheme = "Cookies"; options.LoginPath = new Microsoft.AspNet.Http.PathString("/User/Login"); options.AccessDeniedPath = "/User/AccessDenied"; options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}/{id2?}/{id3?}"); }); DashboardSignalRServer.Start(connectionManager); NodeEditorSignalRServer.Start(connectionManager); MySensorsSignalRServer.Start(connectionManager); LogsSignalRServer.Start(connectionManager); } SystemController.Start(Configuration, serviceProvider); }
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime) { var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); // Add new mappings provider.Mappings[".ps1"] = "text/plain"; provider.Mappings[".psm1"] = "text/plain"; provider.Mappings[".psd1"] = "text/plain"; provider.Mappings[".log"] = "text/plain"; provider.Mappings[".yml"] = "text/plain"; loggerFactory.AddNLog(); app.UseResponseCompression(); app.UseStatusCodePages(async context => { if (context.HttpContext.Response.StatusCode == 404 && !context.HttpContext.Request.Path.StartsWithSegments("/api")) { var response = context.HttpContext.Response; response.StatusCode = 200; var filePath = env.ContentRootPath + "/index.html"; response.ContentType = "text/html; charset=utf-8"; var file = File.ReadAllText(filePath); await response.WriteAsync(file); } else { await context.Next(context.HttpContext); } }); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(env.ContentRootPath), RequestPath = new PathString(""), ServeUnknownFileTypes = true, ContentTypeProvider = provider }); var dashboardService = app.ApplicationServices.GetService(typeof(IDashboardService)) as IDashboardService; if (dashboardService?.DashboardOptions?.PublishedFolders != null) { foreach (var publishedFolder in dashboardService.DashboardOptions.PublishedFolders) { app.UseStaticFiles(new StaticFileOptions { RequestPath = publishedFolder.RequestPath, FileProvider = new PhysicalFileProvider(publishedFolder.Path), ServeUnknownFileTypes = true, ContentTypeProvider = provider }); } } app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()); app.UseSignalR(routes => { routes.MapHub <DashboardHub>("/dashboardhub"); }); app.UseWebSockets(); app.UseSession(); app.UseMvc(); }
public void Configure(IApplicationBuilder app) { app.UseAuthentication(); app.UseWebSockets(); app.UseSignalR(routes => routes.MapDotNetifyHub()); app.UseDotNetify(config => { config.RegisterAssembly("DotNetify.DevApp.ViewModels"); var tokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthServer.SecretKey)), ValidateIssuerSigningKey = true, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(0) }; // Middleware to do authenticate token in incoming request headers. config.UseJwtBearerAuthentication(tokenValidationParameters); // Filter to check whether user has permission to access view models with [Authorize] attribute. config.UseFilter <AuthorizeFilter>(); // Middleware to log incoming/outgoing message; default to Sytem.Diagnostic.Trace. config.UseDeveloperLogging(); // Demonstration middleware that extracts auth token from incoming request headers. config.UseMiddleware <ExtractAccessTokenMiddleware>(tokenValidationParameters); // Demonstration filter that passes access token from the middleware to the ViewModels.SecurePageVM class instance. config.UseFilter <SetAccessTokenFilter>(); }); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, HotModuleReplacementClientOptions = new Dictionary <string, string> { { "reload", "true" } }, }); app.UseStaticFiles(); app.Run(async(context) => { var uri = context.Request.Path.ToUriComponent(); if (uri.EndsWith(".map")) { return; } else if (uri.EndsWith("_hmr") || uri.Contains("hot-update")) // Fix HMR for deep links. { context.Response.Redirect(Regex.Replace(uri, ".+/dist", "/dist")); } using (var reader = new StreamReader(File.OpenRead("wwwroot/index.html"))) await context.Response.WriteAsync(reader.ReadToEnd()); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // 初始化ABP框架 app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // 启用CORS app.UseCors(_defaultCorsPolicyName); // 启用静态文件 app.UseStaticFiles(); // 启用校验 app.UseAuthentication(); app.UseJwtTokenMiddleware(); // 如果使用Identity Server4 if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"])) { app.UseJwtTokenMiddleware("IdentityBearer"); app.UseIdentityServer(); } app.UseAbpRequestLocalization(); app.UseSignalR(routes => { routes.MapHub <AbpCommonHub>("/signalr"); }); ////Hangfire dashboard &server(Enable to use Hangfire instead of default job manager) //app.UseHangfireDashboard("/hangfire", new DashboardOptions //{ // Authorization = new[] { new AbpHangfireAuthorizationFilter(PermissionNames.Pages_Administration_HangfireDashboard) } //}); //app.UseHangfireServer(); app.UseMvc(routes => { routes.MapRoute( name: "defaultWithArea", template: "{area}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // 使中间件能够作为JSON端点提供生成的Swagger app.UseSwagger(); // 使中间件能够提供swagger-ui(HTML、JS、CSS等) app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "YoyoCmsTemplate API V1"); options.SwaggerEndpoint("/swagger/v2/swagger.json", "切换到v2"); //options.DefaultModelExpandDepth(2); //options.DefaultModelRendering(ModelRendering.Model); //options.DefaultModelsExpandDepth(-1); //options.DisplayOperationId(); //options.DisplayRequestDuration(); //options.DocExpansion(DocExpansion.None); //options.EnableDeepLinking(); //options.EnableFilter(); //options.ShowExtensions(); //options.EnableValidator(); //options.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Head); options.IndexStream = () => Assembly.GetExecutingAssembly() .GetManifestResourceStream("LTMCompanyName.YoyoCmsTemplate.Web.Host.wwwroot.swagger.ui.index.html"); }); // URL: /swagger }
// 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(); } app.UseCors("AllowAllOrigins"); app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "Scripts")) }); app.UseSpaStaticFiles(); app.UseAuthentication(); app.UseSwagger(); app.UseStatusCodePages(); app.UseSignalR(routes => { routes.MapHub <NotificationHub>("/notifications"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v3/swagger.json", "MicrosoftGraph_Security_API_Sample V3"); }); // enable SPA service if it is client dev environment var clientEnv = Environment.GetEnvironmentVariable("CLIENT_ENVIRONMENT"); if (true)//(clientEnv == "Development") { app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); } app.Run(async(context) => { context.Response.ContentType = "text/html"; await context.Response.SendFileAsync(Path.Combine("d:\\temp", "index.html")); }); }
// 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(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSession(); app.UseCors("AllowSpecificOrigins"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "Play", template: "playpage", defaults: new { controller = "Home", action = "Play" }); routes.MapRoute( name: "PlayUser", template: "playuserpage", defaults: new { controller = "Home", action = "PlayUser" }); routes.MapRoute( name: "SearchRoomDetails", template: "searchroomlist/{searchText?}/{roomFilter?}/{roomQuickFilter?}", defaults: new { controller = "Home", action = "SearchRoom" }); routes.MapRoute( name: "SearchStoryDetails", template: "searchstorylist/{roomId?}/{searchText?}", defaults: new { controller = "Home", action = "SearchStory" }); routes.MapRoute( name: "FilterRoomDetails", template: "roomquickfilter/{searchText?}/{roomFilter?}/{roomQuickFilter?}", defaults: new { controller = "Home", action = "DashboardRoomFilterDetails" }); routes.MapRoute( name: "CreateNewRoom", template: "createnewroom", defaults: new { controller = "Home", action = "CreateNewRoom" }); routes.MapRoute( name: "ImportStory", template: "importstory/{fileType?}", defaults: new { controller = "Home", action = "ImportStoryDialog" }); routes.MapRoute( name: "CardValue", template: "getcardvalue/{type?}", defaults: new { controller = "Home", action = "GetCardValue" }); routes.MapRoute( name: "AddRoomDetails", template: "addroomdetails/{roomName?}/{roomDescription?}/{minutes?}/{cardtype?}/{players?}", defaults: new { controller = "Home", action = "UpdateRoomDetails" }); routes.MapRoute( name: "RemoveStoryInDashboard", template: "dashboard/removestory/{storyId?}/{createdBy?}/{roomId?}", defaults: new { controller = "Home", action = "RemoveStoryInDashboard" }); routes.MapRoute( name: "RemoveRoomInDashboard", template: "dashboard/deleteroom/{roomId?}", defaults: new { controller = "Home", action = "DeleteRoom" }); routes.MapRoute( name: "Import Story Details", template: "importstorydetails/{file?}/{roomId?}/{activeUserId?}/{fileType?}", defaults: new { controller = "Home", action = "GetImportDetails" }); routes.MapRoute( name: "downloadexcel", template: "download/{name?}/{extension?}", defaults: new { controller = "Home", action = "DownloadFiles" }); routes.MapRoute( name: "GetRequestedStory", template: "play/getstory/{roomId?}/{storyId?}/{filter?}/{checkPendingStory?}/{searchText?}/{userId?}", defaults: new { controller = "Home", action = "GetRequestedStory" }); routes.MapRoute( name: "GetFilteredStory", template: "play/storieslist/{roomId?}/{filter?}", defaults: new { controller = "Home", action = "FilterStories" }); routes.MapRoute( name: "GetTeamAverageList", template: "teamavglist/{roomId?}/{storyId?}", defaults: new { controller = "Home", action = "GetTeamAverageList" }); routes.MapRoute( name: "GetRoomPlayerDetails", template: "getplayerdetails/{roomId?}/{storyId?}/{chartView?}/{userId?}", defaults: new { controller = "Home", action = "GetRoomPlayerDetails" }); routes.MapRoute( name: "StartGame", template: "startplan/{roomId?}/{currentStoryId?}", defaults: new { controller = "Home", action = "StartGame" }); routes.MapRoute( name: "PauseGame", template: "pauseplan/{roomId?}/{currentStoryId?}", defaults: new { controller = "Home", action = "PauseGame" }); routes.MapRoute( name: "ResumeGame", template: "resumeplan/{roomId?}/{currentStoryId?}", defaults: new { controller = "Home", action = "ResumeGame" }); routes.MapRoute( name: "StopGame", template: "stopplan/{roomId?}/{currentStoryId?}/{filter?}", defaults: new { controller = "Home", action = "StopGame" }); routes.MapRoute( name: "EndGame", template: "endgame/{roomId?}/{currentStoryId?}", defaults: new { controller = "Home", action = "EndGame" }); routes.MapRoute( name: "ResetStory", template: "resetstory/{roomId?}/{currentStoryId?}/{nextStoryId?}/{filter?}/{checkPendingStory?}/{searchText?}", defaults: new { controller = "Home", action = "ResetStory" }); routes.MapRoute( name: "ResetEstimatedStory", template: "resetestimatedstory/{roomId?}/{currentStoryId?}/{nextStoryId?}/{searchText?}", defaults: new { controller = "Home", action = "ResetEstimatedStory" }); routes.MapRoute( name: "RemoveStory", template: "removestory/{storyId?}", defaults: new { controller = "Home", action = "RemoveStory" }); routes.MapRoute( name: "CompleteVote", template: "completevote/{roomId?}/{storyId?}/{currentStoryIndex?}/{filter?}", defaults: new { controller = "Home", action = "CompleteVotingProcess" }); routes.MapRoute( name: "EditAverageEstimation", template: "editavgestimation/{roomId?}/{storyId?}/{estimatedPoint?}", defaults: new { controller = "Home", action = "EditAverageEstimation" }); routes.MapRoute( name: "FinishVoting", template: "finishvoting/{roomId?}/{storyId?}/{currentStoryIndex?}/{filter?}", defaults: new { controller = "Home", action = "FinishVoting" }); routes.MapRoute( name: "UpdateVote", template: "updatevote/{roomId?}/{storyId?}/{estimatedPoint?}/{userId?}", defaults: new { controller = "Home", action = "UpdateVote" }); }); app.UseFileServer(); app.UseSignalR(routes => { routes.MapHub <SignalRCommonHub>("/refresh"); }); app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, DefaultContentType = "plain/text", FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "Controllers")), RequestPath = "/Controllers" }); app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, DefaultContentType = "plain/text", FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "Views")), RequestPath = "/Views" }); }
// 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) { if (env.IsDevelopment()) { app.Map("/allservices", builder => builder.Run(async context => { context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync($"<h1>所有服务{Services.Count}个</h1><table><thead><tr><th>类型</th><th>生命周期</th><th>Instance</th></tr></thead><tbody>"); foreach (var svc in Services) { await context.Response.WriteAsync("<tr>"); await context.Response.WriteAsync($"<td>{svc.ServiceType.FullName}</td>"); await context.Response.WriteAsync($"<td>{svc.Lifetime}</td>"); await context.Response.WriteAsync($"<td>{svc.ImplementationType?.FullName}</td>"); await context.Response.WriteAsync("</tr>"); } await context.Response.WriteAsync("</tbody></table>"); })); } //添加文件日志 loggerFactory.AddFile(Configuration.GetSection("FileLogging")); //配置FluentValidation的本地化 app.ConfigLocalizationFluentValidation(); //注册管道是有顺序的 if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } //检查到相应配置启用https跳转 if (Configuration.GetValue("UseHttpsRedirection", false) && (Configuration.GetSection("RafHost").GetSection("Endpoints").GetSection("Https") .GetValue("IsEnabled", false) || Environment.IsDevelopment())) { //app.UseHsts(); HstsBuilderExtensions.UseHsts(app); //注册强制Https跳转到管道 app.UseHttpsRedirection(); } //注册响应压缩到管道 app.UseResponseCompression(); //注册内容安全策略到管道 // Content Security Policy app.UseCsp(csp => { // If nothing is mentioned for a resource class, allow from this domain csp.ByDefaultAllow .FromSelf(); // Allow JavaScript from: csp.AllowScripts .FromSelf() //This domain .AllowUnsafeInline() .AllowUnsafeEval() .From("localhost:5000") //These two domains .From("localhost:5001") .From("localhost:5002") .From("localhost:5003") .From("localhost:5004") .From("localhost:5005") .From("ajax.aspnetcdn.com") .From("cdnjs.cloudflare.com"); //.AddNonce();//此项与AllowUnsafeInline冲突,会被AllowUnsafeInline选项覆盖 // CSS allowed from: csp.AllowStyles .FromSelf() .AllowUnsafeInline() .From("localhost:5000") //These two domains .From("localhost:5001") .From("localhost:5002") .From("localhost:5003") .From("localhost:5004") .From("localhost:5005") .From("ajax.aspnetcdn.com") .From("fonts.googleapis.com") .From("cdnjs.cloudflare.com"); //.AddNonce();//此项与AllowUnsafeInline冲突,会被AllowUnsafeInline选项覆盖 csp.AllowImages .FromSelf() .DataScheme() .From("localhost:5000") //These two domains .From("localhost:5001") .From("localhost:5002") .From("localhost:5003") .From("localhost:5004") .From("localhost:5005") .From("ajax.aspnetcdn.com"); // HTML5 audio and video elemented sources can be from: csp.AllowAudioAndVideo .FromNowhere(); //Nowhere, no media allowed // Contained iframes can be sourced from: csp.AllowFrames .FromSelf(); // Allow AJAX, WebSocket and EventSource connections to: csp.AllowConnections .ToSelf() .To("ws://localhost:5000") .To("wss://localhost:5001") ; // Allow fonts to be downloaded from: csp.AllowFonts .FromSelf() .From("fonts.gstatic.com") .From("ajax.aspnetcdn.com"); // Allow object, embed, and applet sources from: csp.AllowPlugins .FromNowhere(); // Allow other sites to put this in an iframe? csp.AllowFraming .FromAnywhere(); // Block framing on other sites, equivalent to X-Frame-Options: DENY if (env.IsDevelopment()) { // Do not block violations, only report // This is a good idea while testing your CSP // Remove it when you know everything will work //csp.SetReportOnly(); // Where should the violation reports be sent to? //csp.ReportViolationsTo("/csp-report"); } // Do not include the CSP header for requests to the /api endpoints //csp.OnSendingHeader = context => //{ // context.ShouldNotSend = context.HttpContext.Request.Path.StartsWithSegments("/api"); // return Task.CompletedTask; //}; }); //注册请求本地化到管道 var locOptions = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >(); app.UseRequestLocalization(locOptions.Value); //注册默认404页面到管道 app.UseStatusCodePages(async context => { if (context.HttpContext.Response.StatusCode != (int)HttpStatusCode.NotFound) { return; } PathString pathString = "/Home/NotFound"; QueryString queryString = new QueryString(); PathString originalPath = context.HttpContext.Request.Path; QueryString originalQueryString = context.HttpContext.Request.QueryString; context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature() { OriginalPathBase = context.HttpContext.Request.PathBase.Value, OriginalPath = originalPath.Value, OriginalQueryString = (originalQueryString.HasValue ? originalQueryString.Value : null) }); context.HttpContext.Request.Path = pathString; context.HttpContext.Request.QueryString = queryString; try { await context.Next(context.HttpContext); } finally { context.HttpContext.Request.QueryString = originalQueryString; context.HttpContext.Request.Path = originalPath; context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(null); } }); //注册开发环境文件浏览器 if (Environment.IsDevelopment()) { var dir = new DirectoryBrowserOptions(); dir.FileProvider = new PhysicalFileProvider(Environment.ContentRootPath); dir.RequestPath = "/dir"; app.UseDirectoryBrowser(dir); var contentTypeProvider = new FileExtensionContentTypeProvider(); contentTypeProvider.Mappings.Add(".log", "text/plain"); var devStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider(Environment.ContentRootPath), RequestPath = "/dir", ServeUnknownFileTypes = true, DefaultContentType = "application/octet-stream", ContentTypeProvider = contentTypeProvider }; app.UseStaticFiles(devStaticFileOptions); } //注册开发环境的npm和bower资源 if (Environment.IsDevelopment()) { var npmContentTypeProvider = new FileExtensionContentTypeProvider(); var npmStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider(Environment.ContentRootPath + "/node_modules"), RequestPath = "/npm", ServeUnknownFileTypes = false, ContentTypeProvider = npmContentTypeProvider }; app.UseStaticFiles(npmStaticFileOptions); var bowerContentTypeProvider = new FileExtensionContentTypeProvider(); var bowerStaticFileOptions = new StaticFileOptions { FileProvider = new PhysicalFileProvider(Environment.ContentRootPath + "/bower_components"), RequestPath = "/bower", ServeUnknownFileTypes = false, ContentTypeProvider = bowerContentTypeProvider }; app.UseStaticFiles(bowerStaticFileOptions); } //注册静态文件到管道(wwwroot文件夹) app.UseStaticFiles(); //注册Cookie策略到管道(GDPR) app.UseCookiePolicy(); //注册跨域策略到管道 app.UseCors("CorsPolicy"); //注册IdentityServer4到管道 app.UseIdentityServer(); //注册SignalR到管道 app.UseSignalR(routes => { routes.MapHub <ChatHub>("/chatHub"); }); //注册自定义中间件到管道 app.UseAntiforgeryTokenGenerateMiddleware(); //注册MVC到管道 app.UseMvc(routes => { routes .MapRoute( name: "area", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ) .MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
/// <summary> /// 应用AspNetCore的服务业务 /// </summary> /// <param name="app">Asp应用程序构建器</param> public override void UsePack(IApplicationBuilder app) { Action <HubRouteBuilder> hubRouteBuildAction = GetHubRouteBuildAction(app.ApplicationServices); app.UseSignalR(hubRouteBuildAction); }
// 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(); #region tokenProvider var secretKey = "mysupersecret_secretkey!123"; var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)); var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "CloudMine", // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "ExampleAudience", // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here: ClockSkew = TimeSpan.Zero }; app.UseCookieAuthentication(new CookieAuthenticationOptions { LoginPath = new Microsoft.AspNetCore.Http.PathString("/Home/Login"), AutomaticAuthenticate = true, AutomaticChallenge = true, AuthenticationScheme = "Cookie", CookieName = "access_token", TicketDataFormat = new CustomJwtDataFormat( SecurityAlgorithms.HmacSha256, tokenValidationParameters) }); app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters }); //var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)); var options = new TokenProviderOptions { Audience = "ExampleAudience", Issuer = "CloudMine", SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), }; // Add JWT generation endpoint: app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options)); #endregion if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseCors("AllowAnyOrigin"); app.UseStaticFiles(); app.UseIdentity(); app.UseWebSockets(); app.UseSignalR(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "restAction", template: "api/{controller}/{action}/"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { UseProxyForwardingAndDomainPathHelper(app); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); #if DEBUG app.UseDevReload(new DevReloadOptions { Directory = "./", IgnoredSubDirectories = new string[] { ".git", ".node_modules", "bin", "obj" }, StaticFileExtensions = new string[] { "css", "js", "html", "cshtml" }, MaxConnectionFailedCount = 20, CheckIntervalDelay = 2000, PopoutHtmlTemplate = @"<div id='reload' class='toast' role='alert' aria-live='assertive' aria-atomic='true' data-autohide='false' data-animation='true' style='position: absolute; top: 0; right: 0; z-index: 9999'> <div class='toast-header'> <svg class='bd-placeholder-img rounded mr-2' width='20' height='20' xmlns='http://www.w3.org/2000/svg' preserveAspectRatio='xMidYMid slice' focusable='false' role='img'><rect width = '100%' height='100%' fill='red'></rect></svg> <strong class='mr-auto'>DevReload</strong> <small>just now</small> <button type='button' class='ml-2 mb-1 close' data-dismiss='toast' aria-label='Close'> <span aria-hidden='true'>×</span> </button> </div> <div class='toast-body'> DevReload - Reloading page... </div> </div> <script> $('#reload').toast('hide'); </script>", TemplateActivationJSFragment = @"$('#reload').toast('show');" }); #endif //app.UseExceptionHandler("/dotnet/Home/Error"); //app.UseBrowserLink(); } else { app.UseExceptionHandler("/dotnet/Home/Error"); } app.UseStatusCodePagesWithReExecute("/dotnet/Home/Error/{0}"); #if DEBUG if (env.IsDevelopment()) { app.UseHttpsRedirection(); } #endif //app.UseStaticFiles(); app.UseServerTiming(); app.UseSession(); app.UseAuthentication(); app.UseSignalR(routes => { routes.PrepareSignalRForInkBall("/dotnet/"); }); app.Map("/dotnet", main => { main.UseIdentityManager(); main.UseStaticFiles(); main.UseMvcWithDefaultRoute(); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSignalR(options => options.MapHub <EchoHub>("/echo")); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IHttpContextAccessor accessor, IApplicationLifetime lifetime) { #region Environment if (env.IsDevelopment()) { // 在开发环境中,使用异常页面,这样可以暴露错误堆栈信息,所以不要放在生产环境。 app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // 在非开发环境中,使用HTTP严格安全传输(or HSTS) 对于保护web安全是非常重要的。 // 强制实施 HTTPS 在 ASP.NET Core,配合 app.UseHttpsRedirection //app.UseHsts(); } #endregion #region Consul //ConsulModel consulModel = new ConsulModel() //{ // Ip = Configuration["Consul:IP"], // Port = Convert.ToInt32(Configuration["Consul:Port"]) //}; //HealthModel healthModel = new HealthModel() //{ // Ip = Configuration["Service:IP"], // Port = Convert.ToInt32(Configuration["Service:Port"]), // Name = Configuration["Service:Name"], //}; //app.RegisterConsul(lifetime, healthModel, consulModel); #endregion #region HttpContext HttpAccessor._Accessor = accessor; #endregion #region IpRateLimitOptions app.UseIpRateLimiting(); #endregion #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { //根据版本名称正序 遍历展示 typeof(ApiVersions).GetEnumNames().OrderBy(e => e).ToList().ForEach(version => { c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{Def.ApiName} {version}"); }); // 将swagger首页,设置成我们自定义的页面:解决方案名+.index.html // 这里是配合MiniProfiler进行性能监控的 c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream(Def.ApiName + Def.HtmlName); // 路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉 c.RoutePrefix = ""; // Display c.DefaultModelExpandDepth(2); c.DefaultModelRendering(ModelRendering.Model); c.DefaultModelsExpandDepth(-1); c.DisplayOperationId(); c.DisplayRequestDuration(); c.DocExpansion(DocExpansion.None); c.ShowExtensions(); }); #endregion #region MiniProfiler app.UseMiniProfiler(); #endregion #region Authen app.UseAuthentication(); #endregion #region CORS if (Def.AllowedCrosFlg) { app.UseCors(Def.CorsName); } #endregion #region WebSite // 请求与返回 if (Def.RequestResponseMiddleware) { app.UseReuestResponseLog(); } // JWT认证 if (Def.JwtAuthMiddleware) { app.UseJwtTokenAuth(); } // 重定向 //app.UseHttpsRedirection(); // 静态文件 app.UseStaticFiles(); // Cookie if (Def.CookieFlg) { app.UseCookiePolicy(); } // Session if (Def.SessionFlg) { app.UseSession(); } // 返回错误码 app.UseStatusCodePages(); #endregion #region NLog Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); loggerFactory.AddNLog(); env.ConfigureNLog(Def.NLogConfigName); #endregion #region SignalR if (Def.SignalrFlg) { app.UseSignalR(routes => { //如果你不用/api/xxx的这个规则的话,会出现跨域问题 routes.MapHub <ChatHub>("/ChatHub"); }); } #endregion #region Mvc app.UseMvc(); #endregion #region Payment Gateway if (Def.PaymentGatewayFlg) { app.UsePaySharp(); } #endregion }
public static IApplicationBuilder MapSignalR(this IApplicationBuilder app) { app.UseSignalR(routes => { routes.MapHub <OnlineHub>("onlinehub"); }); return(app); }
// 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.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } //Return all errors as Json response app.UseMiddleware <ApiErrorWrappingMiddleware>(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); //Handle all requests like a $(Platform) and Modules/$({ module.ModuleName }) as static files in correspond folder app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(env.MapPath("~/js")), RequestPath = new PathString($"/$(Platform)/Scripts") }); var localModules = app.ApplicationServices.GetRequiredService <ILocalModuleCatalog>().Modules; foreach (var module in localModules.OfType <ManifestModuleInfo>()) { app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(module.FullPhysicalPath), RequestPath = new PathString($"/Modules/$({ module.ModuleName })") }); } app.UseDefaultFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); //Force migrations using (var serviceScope = app.ApplicationServices.CreateScope()) { var platformDbContext = serviceScope.ServiceProvider.GetRequiredService <PlatformDbContext>(); var securityDbContext = serviceScope.ServiceProvider.GetRequiredService <SecurityDbContext>(); platformDbContext.Database.Migrate(); securityDbContext.Database.Migrate(); } //Using Smidge runtime bundling library for bundling modules js and css files app.UseSmidge(bundles => { app.UseModulesContent(bundles); }); app.UseSmidgeNuglify(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(c => c.RouteTemplate = "docs/{documentName}/docs.json"); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/docs/v1/docs.json", "Explore"); c.RoutePrefix = "docs"; c.EnableValidator(); c.IndexStream = () => { var type = GetType().GetTypeInfo().Assembly .GetManifestResourceStream("VirtoCommerce.Platform.Web.wwwroot.swagger.index.html"); return(type); }; c.DocumentTitle = "VirtoCommerce Solution REST API documentation"; c.InjectStylesheet("/swagger/vc.css"); c.ShowExtensions(); c.DocExpansion(DocExpansion.None); }); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangfireAuthorizationHandler() } }); app.UseHangfireServer(new BackgroundJobServerOptions { // Create some queues for job prioritization. // Normal equals 'default', because Hangfire depends on it. Queues = new[] { JobPriority.High, JobPriority.Normal, JobPriority.Low } }); app.UseDbTriggers(); //Register platform settings app.UsePlatformSettings(); app.UseModules(); //Register platform permissions app.UsePlatformPermissions(); //Setup SignalR hub app.UseSignalR(routes => { routes.MapHub <PushNotificationHub>("/pushNotificationHub"); }); //Seed default users app.UseDefaultUsersAsync().GetAwaiter().GetResult(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework. app.UseCors(_defaultCorsPolicyName); // Enable CORS! app.UseStaticFiles(); app.UseAuthentication(); app.UseAbpRequestLocalization(); // config hangfire use httpjob ConfigHangfire.UseHangfireSettings(app, env, loggerFactory); #if FEATURE_SIGNALR // Integrate with OWIN app.UseAppBuilder(ConfigureOwinServices); #elif FEATURE_SIGNALR_ASPNETCORE app.UseSignalR(routes => { routes.MapHub <AbpCommonHub>("/signalr"); }); #endif app.UseMvc(routes => { routes.MapRoute( name: "defaultWithArea", template: "{area}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); if (_appConfiguration["app:Swagger"] == "Grpc.Api") { var magicOnion = app.ApplicationServices.GetService <MagicOnionServiceDefinition>(); //grpc var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) var xmlPath = Path.Combine(basePath, "JPGZService.Application.xml"); app.UseMagicOnionSwagger(magicOnion.MethodHandlers, new MagicOnion.HttpGateway.Swagger.SwaggerOptions("Grpc.Server", "GrpcApiDoc", "/") { Info = new MagicOnion.HttpGateway.Swagger.Schemas.Info() { title = "ABP.Grpc.Service", version = "v1", description = "ABP.Grpc Service", contact = new MagicOnion.HttpGateway.Swagger.Schemas.Contact { name = "gnsilence", email = "*****@*****.**", url = "" }, license = new MagicOnion.HttpGateway.Swagger.Schemas.License { name = "License", url = "" } }, XmlDocumentPath = xmlPath }); app.UseMagicOnionHttpGateway(magicOnion.MethodHandlers, new Channel("localhost:" + _appConfiguration["Grpc:GrpcBindPort"], ChannelCredentials.Insecure)); } // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUI(options => { options.InjectJavascript("/swagger/ui/abp.js"); options.InjectJavascript("/swagger/ui/on-complete.js"); options.SwaggerEndpoint("/swagger/v1/swagger.json", "ABPService API V1"); }); // URL: /swagger }
public static IApplicationBuilder UseHelpers(this IApplicationBuilder app) => app.UseSignalR(c => c.MapHub <DataUpdatesHub>("/dataUpdates"));
// 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, IOptionsSnapshot <WorkOption> option) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { //app.UseExceptionHandler("/Home/Error"); app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; var error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { var ex = error.Error; //当异常为微信类型异常时候尝试重新注册刷新AccessToken if (ex is WeixinException) { try { RegisterWeixinAccessToken(option); } catch (Exception e) { ex = e; } } await context.Response.WriteAsync(new ResultJSON <string>() { Code = 500, Msg = ex.Message, Data = ex.Source }.ToString(), Encoding.UTF8); } }); }); } app.UseSession(); app.UseStaticFiles(); app.UseWebSockets(); app.UseSignalR(routes => { routes.MapHub <PrintHub>("/hubs/print"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); #region 微信相关 RegisterWeixinAccessToken(option); #endregion }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context) { app.InitializeSimpleInjectorContainer(_container, Configuration); _container.Verify(); app.AddLogging(loggerFactory, Configuration); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, ReactHotModuleReplacement = true }); } else { if (!string.IsNullOrWhiteSpace(Configuration["showDetailedErrors"])) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); // Authentication settings app.UseCookieAuthentication(_tokenAuthenticationProvider.CookieAuthenticationOptions); app.UseJwtBearerAuthentication(_tokenAuthenticationProvider.JwtBearerOptions); app.UseIdentity(); app.UseValidateAntiforgeryToken(); // SignalR app.UseWebSockets(); app.UseSignalR(); app.UseFluentScheduler(_container); app.UseStatusCodePages(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.MapWhen( httpContext => !new[] { 400, 401, 402, 403 }.Contains(httpContext.Response.StatusCode) && // is not permission error !(httpContext.Response.StatusCode == 404 && Path.HasExtension(httpContext.Request.Path.Value)), // is not failed file request appBuilder => { // then try spa fallback appBuilder.UseMvc(routes => { routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); }); //app.MapWhen(httpContext => httpContext.Response.StatusCode == 404 // && Path.HasExtension(httpContext.Request.Path.Value), // appBuilder => // { // appBuilder.Use((context, next) => // { // context.Request.Path = new PathString("/index.html"); // Console.WriteLine("Path changed to:" + context.Request.Path.Value); // return next(); // }); // branch.UseStaticFiles(); // }); //app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api"), //app.MapWhen(c => c.Request.Path.Value.eHasValue, b => ) DbInitializer.Initialize(context); }
public static IApplicationBuilder UseBindKraft(this IApplicationBuilder app, IHostingEnvironment env) { //AntiforgeryService //app.Use(next => context => //{ // if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase)) // { // AntiforgeryTokenSet tokens = app.ApplicationServices.GetService<IAntiforgery>().GetAndStoreTokens(context); // context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); // } // return next(context); //}); _KraftGlobalConfigurationSettings.EnvironmentSettings = new KraftEnvironmentSettings(env.ApplicationName, env.ContentRootPath, env.EnvironmentName, env.WebRootPath); try { ILoggerFactory loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); DiagnosticListener diagnosticListener = app.ApplicationServices.GetService <DiagnosticListener>(); //First statement to register Error handling !!!Keep at the top!!! app.UseMiddleware <KraftExceptionHandlerMiddleware>(loggerFactory, new ExceptionHandlerOptions(), diagnosticListener); AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve += AppDomain_OnAssemblyResolve; if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToWww) { RewriteOptions rewrite = new RewriteOptions(); rewrite.AddRedirectToWwwPermanent(); app.UseRewriter(rewrite); } if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToHttps) { app.UseForwardedHeaders(); app.UseHsts(); app.UseHttpsRedirection(); } ExtensionMethods.Init(app, _Logger); app.UseBindKraftLogger(env, loggerFactory, ERRORURLSEGMENT); app.UseBindKraftProfiler(env, loggerFactory, _MemoryCache); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } _Builder = app; BundleCollection bundleCollection = app.UseBundling(env, loggerFactory.CreateLogger("Bundling"), _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlCssJsSegment, _KraftGlobalConfigurationSettings.GeneralSettings.EnableOptimization); bundleCollection.EnableInstrumentations = env.IsDevelopment(); //Logging enabled #region Initial module registration foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders) { if (!Directory.Exists(dir)) { throw new Exception($"No \"{dir}\" directory found! The CoreKraft initialization cannot continue."); } } string kraftUrlSegment = _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlSegment; try { KraftModuleCollection modulesCollection = app.ApplicationServices.GetService <KraftModuleCollection>(); Dictionary <string, string> moduleKey2Path = new Dictionary <string, string>(); IApplicationLifetime applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>(); lock (_SyncRoot) { foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders) { string[] moduleDirectories = Directory.GetDirectories(dir); foreach (string subdirectory in moduleDirectories) { DirectoryInfo moduleDirectory = new DirectoryInfo(subdirectory); if (moduleDirectory.Name != null && moduleDirectory.Name.Equals("_PluginsReferences", StringComparison.InvariantCultureIgnoreCase)) { continue; } ICachingService cachingService = app.ApplicationServices.GetService <ICachingService>(); KraftModule kraftModule = modulesCollection.GetModule(moduleDirectory.Name); if (kraftModule != null) { continue; } kraftModule = modulesCollection.RegisterModule(dir, moduleDirectory.Name, cachingService); if (kraftModule == null || !kraftModule.IsInitialized) { _Logger.LogInformation($"Module not created for directory \"{moduleDirectory.Name}\" because of missing configuration files."); continue; } KraftStaticFiles.RegisterStaticFiles(app, moduleDirectory.FullName, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModuleImages); KraftStaticFiles.RegisterStaticFiles(app, moduleDirectory.FullName, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModulePublic); moduleKey2Path.Add(kraftModule.Key.ToLower(), dir); //The application will restart when some files changed in the modules directory and subdirectories but only in RELEASE //Check if module is initialized Robert if (kraftModule.IsInitialized && !env.IsDevelopment()) { string moduleFullPath = Path.Combine(dir, kraftModule.Key); AttachModulesWatcher(moduleFullPath, false, applicationLifetime); string path2Data = Path.Combine(moduleFullPath, "Data"); if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true)) { throw new SecurityException($"Write access to folder {path2Data} is required!"); } path2Data = Path.Combine(moduleFullPath, "Images"); if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true)) { throw new SecurityException($"Write access to folder {path2Data} is required!"); } AttachModulesWatcher(Path.Combine(moduleFullPath, "Css"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Documentation"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Localization"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "NodeSets"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Scripts"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Templates"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Views"), true, applicationLifetime); } } } //try to construct all modules modulesCollection.ResolveModuleDependencies(); _KraftGlobalConfigurationSettings.GeneralSettings.ModuleKey2Path = moduleKey2Path; } if (!env.IsDevelopment()) { _Configuration.GetReloadToken().RegisterChangeCallback(_ => { RestartReason restartReason = new RestartReason(); restartReason.Reason = "Configuration Changed"; restartReason.Description = $"'appsettings.Production.json' has been altered"; AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_OnAssemblyResolve; RestartApplication(applicationLifetime, restartReason); }, null); } } catch (Exception boom) { KraftLogger.LogError(boom); throw new Exception($"CoreKrafts module construction failed! {boom.Message}"); } #endregion Initial module registration //Configure the CoreKraft routing RouteHandler kraftRoutesHandler = new RouteHandler(KraftMiddleware.ExecutionDelegate(app, _KraftGlobalConfigurationSettings)); app.UseRouter(KraftRouteBuilder.MakeRouter(app, kraftRoutesHandler, kraftUrlSegment)); app.UseSession(); if (_KraftGlobalConfigurationSettings.GeneralSettings.AuthorizationSection.RequireAuthorization) { app.UseAuthentication(); } //KraftKeepAlive.RegisterKeepAliveAsync(builder); //Configure eventually SignalR try { if (_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.UseSignalR) { app.UseSignalR(routes => { MethodInfo mapHub = typeof(HubRouteBuilder).GetMethod("MapHub", new[] { typeof(PathString) }); MethodInfo generic = mapHub.MakeGenericMethod(Type.GetType(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubImplementationAsString)); generic.Invoke(routes, new object[] { new PathString(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubRoute) }); }); } } catch (Exception e) { KraftLogger.LogError("Register signalR middleware. Exception: " + e); } //Signals SignalStartup signalStartup = new SignalStartup(app.ApplicationServices, _KraftGlobalConfigurationSettings); signalStartup.ExecuteSignalsOnStartup(); //End Signals } catch (Exception ex) { KraftLogger.LogError("Method: UseBindKraft ", ex); KraftExceptionHandlerMiddleware.Exceptions[KraftExceptionHandlerMiddleware.EXCEPTIONSONCONFIGURE].Add(ex); } //This is the last statement KraftExceptionHandlerMiddleware.HandleErrorAction(app); return(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseCors("CorsPolicy"); app.UseSignalR(routes => routes.MapHub <ColorHub>("/drawapi")); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //Initializes ABP framework. app.UseAbp(options => { options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseStatusCodePagesWithRedirects("~/Error?statusCode={0}"); app.UseExceptionHandler("/Error"); } app.UseCors(DefaultCorsPolicyName); //Enable CORS! app.UseAuthentication(); app.UseJwtTokenMiddleware(); if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"])) { app.UseJwtTokenMiddleware("IdentityBearer"); app.UseIdentityServer(); } app.UseStaticFiles(); using (var scope = app.ApplicationServices.CreateScope()) { if (scope.ServiceProvider.GetService <DatabaseCheckHelper>().Exist(_appConfiguration["ConnectionStrings:Default"])) { app.UseAbpRequestLocalization(); } } app.UseSignalR(routes => { routes.MapHub <AbpCommonHub>("/signalr"); routes.MapHub <ChatHub>("/signalr-chat"); }); if (WebConsts.HangfireDashboardEnabled) { //Hangfire dashboard &server(Enable to use Hangfire instead of default job manager) app.UseHangfireDashboard(WebConsts.HangfireDashboardEndPoint, new DashboardOptions { Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard) } }); app.UseHangfireServer(); } if (bool.Parse(_appConfiguration["Payment:Stripe:IsActive"])) { StripeConfiguration.SetApiKey(_appConfiguration["Payment:Stripe:SecretKey"]); } if (WebConsts.GraphQL.Enabled) { app.UseGraphQL <MainSchema>(); if (WebConsts.GraphQL.PlaygroundEnabled) { app.UseGraphQLPlayground( new GraphQLPlaygroundOptions()); //to explorer API navigate https://*DOMAIN*/ui/playground } } app.UseMvc(routes => { routes.MapRoute( name: "defaultWithArea", template: "{area}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); if (WebConsts.SwaggerUiEnabled) { // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUI(options => { options.SwaggerEndpoint(_appConfiguration["App:SwaggerEndPoint"], "AbpZeroTemplate API V1"); options.IndexStream = () => Assembly.GetExecutingAssembly() .GetManifestResourceStream("MyCompanyName.AbpZeroTemplate.Web.wwwroot.swagger.ui.index.html"); options.InjectBaseUrl(_appConfiguration["App:ServerRootAddress"]); }); //URL: /swagger } }
// 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, FoodDbContext foodDbContext) { // loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "text/plain"; var errorFeature = context.Features.Get <IExceptionHandlerFeature>(); if (errorFeature != null) { var logger = loggerFactory.CreateLogger("Global exception logger"); logger.LogError(500, errorFeature.Error, errorFeature.Error.Message); } await context.Response.WriteAsync("There was an error"); }); }); } app.UseCors("AllowAllOrigins"); AutoMapper.Mapper.Initialize(mapper => { mapper.CreateMap <FoodItem, FoodItemDto>().ReverseMap(); mapper.CreateMap <FoodItem, FoodItemUpdateDto>().ReverseMap(); mapper.CreateMap <FoodItem, FoodItemCreateDto>().ReverseMap(); mapper.CreateMap <Product, ProductDto>().ReverseMap(); mapper.CreateMap <PeriodicElement, PeriodicElementDto>().ReverseMap(); // mapper.CreateMap<Product, ProductUpdateDto>().ReverseMap(); mapper.CreateMap <Entities.Author, Models.AuthorDto>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}")) .ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.DateOfBirth.GetCurrentAge())); mapper.CreateMap <Entities.Book, Models.BookDto>(); mapper.CreateMap <Models.AuthorForCreationDto, Entities.Author>(); mapper.CreateMap <Models.BookForCreationDto, Entities.Book>(); mapper.CreateMap <Models.BookForUpdateDto, Entities.Book>(); mapper.CreateMap <Entities.Book, Models.BookForUpdateDto>(); }); foodDbContext.EnsureSeedDataForContext(); // IdentityServer4.AccessTokenValidation: authentication middleware for the API. app.UseIdentityServer(); app.UseAuthentication(); app.UseStaticFiles(); app.UseDefaultFiles(); app.UseSignalR(routes => { routes.MapHub <FoodHub>("/foodhub"); }); // 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(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "FoodAPICore V1"); }); app.UseMvcWithDefaultRoute(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //Initializes ABP framework. app.UseAbp(options => { options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization }); app.UseCors(DefaultCorsPolicyName); //Enable CORS! app.UseAuthentication(); app.UseJwtTokenMiddleware(); if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"])) { app.UseJwtTokenMiddleware("IdentityBearer"); app.UseIdentityServer(); } app.UseStaticFiles(); using (var scope = app.ApplicationServices.CreateScope()) { if (scope.ServiceProvider.GetService <DatabaseCheckHelper>().Exist(_appConfiguration["ConnectionStrings:Default"])) { app.UseAbpRequestLocalization(); } } app.UseSignalR(routes => { routes.MapHub <AbpCommonHub>("/signalr"); routes.MapHub <ChatHub>("/signalr-chat"); }); //Hangfire dashboard & server (Enable to use Hangfire instead of default job manager) //app.UseHangfireDashboard("/hangfire", new DashboardOptions //{ // Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard) } //}); //app.UseHangfireServer(); app.UseMvc(routes => { routes.MapRoute( name: "defaultWithArea", template: "{area}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUI(options => { options.SwaggerEndpoint(_appConfiguration["App:SwaggerEndPoint"], "Precise API V1"); options.IndexStream = () => Assembly.GetExecutingAssembly() .GetManifestResourceStream("Precise.Web.wwwroot.swagger.ui.index.html"); options.InjectBaseUrl(_appConfiguration["App:ServerRootAddress"]); }); //URL: /swagger }
public void Configure(IApplicationBuilder app) { //Set up NTLM authentication for WebListener like below. //For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or modify the applicationHost.config to enable NTLM. //Note: This does not work on CoreCLR yet! if ((app.Server as ServerInformation) != null) { var serverInformation = (ServerInformation)app.Server; serverInformation.Listener.AuthenticationManager.AuthenticationTypes = AuthenticationTypes.NTLM; } app.Use(async(context, next) => { //Who will get admin access? For demo sake I'm listing the currently logged on user as the application administrator. But this can be changed to suit the needs. var identity = (ClaimsIdentity)context.User.Identity; #if ASPNET50 //no WindowsIdentity yet on CoreCLR if (identity.GetUserName() == Environment.UserDomainName + "\\" + Environment.UserName) { identity.AddClaim(new Claim("ManageStore", "Allowed")); } #endif await next.Invoke(); }); //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var configuration = new Configuration() .AddJsonFile("config.json") .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values. //Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline. //Note: ErrorPageOptions.ShowAll to be used only at development time. Not recommended for production. app.UseErrorPage(ErrorPageOptions.ShowAll); app.UseServices(services => { // Add EF services to the services container services.AddEntityFramework() .AddSqlServer(); services.AddScoped <MusicStoreContext>(); // Configure DbContext services.SetupOptions <MusicStoreDbContextOptions>(options => { options.DefaultAdminUserName = configuration.Get("DefaultAdminUsername"); options.DefaultAdminPassword = configuration.Get("DefaultAdminPassword"); options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString")); }); // Add Identity services to the services container services.AddIdentitySqlServer <MusicStoreContext, ApplicationUser>() .AddAuthentication(); // Add MVC services to the services container services.AddMvc(); //Add all SignalR related services to IoC. services.AddSignalR(); //Add InMemoryCache //Currently not able to AddSingleTon services.AddInstance <IMemoryCache>(new MemoryCache()); }); //Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the MusicStore sample data SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait(); }
// 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) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseAuthentication(); app.Use( next => { return(async context => { var stopWatch = new Stopwatch(); stopWatch.Start(); context.Response.OnStarting( () => { context.Response.Headers.Add("RequestId", context.TraceIdentifier); stopWatch.Stop(); context.Response.Headers.Add("X-ResponseTime-Ms", stopWatch.ElapsedMilliseconds.ToString()); return Task.CompletedTask; }); await next(context); }); }); app.UseElmah(); app.UseMiniProfiler(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); var jsnlogConfiguration = new JsnlogConfiguration { serverSideMessageFormat = "Url : %url %newline* RequestId : %requestId %entryId %newline*" + "Message : %message %newline* %jsonmessage %newline*" + "Sent: %date, Browser: %userAgent %newline*", serverSideLogger = "WebApp.Jslogger" }; app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); app.UseSignalR(routes => { routes.MapHub <AnonymousHub>("/anonymousHub"); }); app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ); 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) { #region ReuestResponseLog if (Appsettings.app("AppSettings", "Middleware_RequestResponse", "Enabled").ObjToBool()) { app.UseReuestResponseLog();//记录请求与返回数据 } #endregion #region Environment if (env.IsDevelopment()) { // 在开发环境中,使用异常页面,这样可以暴露错误堆栈信息,所以不要放在生产环境。 app.UseDeveloperExceptionPage(); //app.Use(async (context, next) => //{ // //这里会多次调用,这里测试一下就行,不要打开注释 // //var blogs =await _blogArticleServices.GetBlogs(); // var processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; // Console.WriteLine(processName); // await next(); //}); } else { app.UseExceptionHandler("/Error"); // 在非开发环境中,使用HTTP严格安全传输(or HSTS) 对于保护web安全是非常重要的。 // 强制实施 HTTPS 在 ASP.NET Core,配合 app.UseHttpsRedirection // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. //app.UseHsts(); } #endregion #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { //根据版本名称倒序 遍历展示 typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version => { c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName}{version}"); // 将swagger首页,设置成我们自定义的页面,记得这个字符串的写法:解决方案名.index.html c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("JYShop.index.html"); //这里是配合MiniProfiler进行性能监控的,《文章:完美基于AOP的接口性能分析》,如果你不需要,可以暂时先注释掉,不影响大局。 c.RoutePrefix = ""; //路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉 }); }); #endregion #region MiniProfiler app.UseMiniProfiler(); #endregion #region 第三步:开启认证中间件 //此授权认证方法已经放弃,请使用下边的官方验证方法。但是如果你还想传User的全局变量,还是可以继续使用中间件,第二种写法 //app.UseMiddleware<JwtTokenAuth>(); app.UseJwtTokenAuth(); //如果你想使用官方认证,必须在上边ConfigureService 中,配置JWT的认证服务 (.AddAuthentication 和 .AddJwtBearer 二者缺一不可) app.UseAuthentication(); #endregion #region CORS //跨域第二种方法,使用策略,详细策略信息在ConfigureService中 app.UseCors("LimitRequests");//将 CORS 中间件添加到 web 应用程序管线中, 以允许跨域请求。 #region 跨域第一种版本 //跨域第一种版本,请要ConfigureService中配置服务 services.AddCors(); // app.UseCors(options => options.WithOrigins("http://localhost:8021").AllowAnyHeader() //.AllowAnyMethod()); #endregion #endregion // 跳转https //app.UseHttpsRedirection(); // 使用静态文件 app.UseStaticFiles(); // 使用cookie app.UseCookiePolicy(); // 返回错误码 app.UseStatusCodePages();//把错误码返回前台,比如是404 app.UseMvc(); #region SignalR app.UseSignalR(routes => { //这里要说下,为啥地址要写 /api/xxx //因为我前后端分离了,而且使用的是代理模式,所以如果你不用/api/xxx的这个规则的话,会出现跨域问题,毕竟这个不是我的controller的路由,而且自己定义的路由 routes.MapHub <ChatHub>("/api2/chathub"); }); #endregion }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions <SenparcWeixinSetting> senparcWeixinSetting) { app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework. app.UseCors(_defaultCorsPolicyName); // Enable CORS! app.UseStaticFiles(); //使用session app.UseSession(); app.UseAuthentication(); app.UseAbpRequestLocalization(); #if FEATURE_SIGNALR // Integrate with OWIN app.UseAppBuilder(ConfigureOwinServices); #elif FEATURE_SIGNALR_ASPNETCORE app.UseSignalR(routes => { routes.MapHub <AbpCommonHub>("/signalr"); }); #endif //404错跳转配置 //app.UseStatusCodePagesWithRedirects("/GAWX/Error/{0}"); //app.UseStatusCodePagesWithRedirects("/GAWX/Error"); app.UseMvc(routes => { routes.MapRoute( name: "defaultWithArea", template: "{area}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region 微信相关 ////注册微信 //AccessTokenContainer.Register(senparcWeixinSetting.Value.WeixinAppId, senparcWeixinSetting.Value.WeixinAppSecret); //Senparc.Weixin SDK 配置 Senparc.Weixin.Config.IsDebug = true; Senparc.Weixin.Config.DefaultSenparcWeixinSetting = senparcWeixinSetting.Value; //提供网站根目录 if (env.ContentRootPath != null) { Senparc.Weixin.Config.RootDictionaryPath = env.ContentRootPath; } /* 微信配置开始 * * 建议按照以下顺序进行注册,尤其须将缓存放在第一位! */ //RegisterWeixinCache(app); //注册分布式缓存(按需,如果需要,必须放在第一个) ConfigWeixinTraceLog(); //配置微信跟踪日志(按需) RegisterWeixinThreads(); //激活微信缓存及队列线程(必须) RegisterSenparcWeixin(); //注册Demo所用微信公众号的账号信息(按需) //RegisterSenparcWorkWeixin(); //注册Demo所用企业微信的账号信息(按需) //RegisterWeixinPay(); //注册微信支付(按需) //RegisterWeixinThirdParty(); //注册微信第三方平台(按需) /* 微信配置结束 */ #endregion // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUI(options => { options.InjectOnCompleteJavaScript("/swagger/ui/abp.js"); options.InjectOnCompleteJavaScript("/swagger/ui/on-complete.js"); options.SwaggerEndpoint("/swagger/v1/swagger.json", "WeChat API V1"); }); // URL: /swagger app.Run(async(context) => { await System.Threading.Tasks.Task.Run(() => { var url = context.Request.GetAbsoluteUri(); if (url.Contains("/gawechat/") && !url.Contains("/index.html")) { context.Response.Redirect(url.Replace("/gawechat/", "/gawechat/index.html")); } }); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.ApplicationServices .GetService<Db>() .Database .EnsureCreated(); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSignalR(); app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); }