// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(Microsoft.AspNetCore.Builder.IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //If ASP.net router doesn't recognize path, then we are assuming that Angular2 router will know something app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.Contains("/api/")) { context.Request.Path = "/index.html"; // Put your Angular root page here await next(); } }); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseIdentity(); app.UseOAuthValidation(); app.UseOpenIddict(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); // 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(); }
/// <summary> /// Added the middlware that creates and disposes a <see cref="IRenderEngine"/> for each request /// </summary> /// <param name="app">The application.</param> public static void UseJsEngine( this AppBuilder app #if !DOTNETCORE , IRenderEngineFactory renderEngineFactory #endif ) { #if !DOTNETCORE app.Use <RenderEngineMiddleware>(renderEngineFactory); #else app.UseMiddleware <RenderEngineMiddleware>(); #endif }
} // End Sub UseTable public static void UseFileContents(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, string path) { Microsoft.AspNetCore.Http.PathString ps = new Microsoft.AspNetCore.Http.PathString(path); app.Use(async(context, next) => { if (context.Request.Path == ps) { string filePath = context.Request.Query["file"].ToString(); string content = await System.IO.File.ReadAllTextAsync(filePath); context.Response.StatusCode = 200; context.Response.ContentType = "text/plain; charset=utf-8"; await context.Response.WriteAsync(content); } else { await next(); } }); } // End Sub UseTable
} // End Task Echo public static void UseEcho(this Microsoft.AspNetCore.Builder.IApplicationBuilder app) { app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { System.Net.WebSockets.WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); } // End Sub UseEcho
} // End Sub UseRansackSearchAndReplace public static void UseRansackSearch( this Microsoft.AspNetCore.Builder.IApplicationBuilder app , string path) { app.Use(async(context, next) => { if (context.Request.Path.Equals(new Microsoft.AspNetCore.Http.PathString(path), System.StringComparison.InvariantCultureIgnoreCase)) { if (context.WebSockets.IsWebSocketRequest) { System.Net.WebSockets.WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Ransack(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); } // End Sub UseRansackSearch
} // End Task GetTableAsync public static void UseTable(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, string path) { Microsoft.AspNetCore.Http.PathString ps = new Microsoft.AspNetCore.Http.PathString(path); app.Use(async(context, next) => { if (context.Request.Path == ps) { if (context.WebSockets.IsWebSocketRequest) { System.Net.WebSockets.WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); await GetTableAsync(context, webSocket); } else { context.Response.StatusCode = 400; } } else { await next(); } }); } // End Sub UseTable
public static void UseOpenFolderOrFileExtensions( this Microsoft.AspNetCore.Builder.IApplicationBuilder app , string path) { app.Use(async(context, next) => { if (context.Request.Path.Equals(new Microsoft.AspNetCore.Http.PathString(path), System.StringComparison.InvariantCultureIgnoreCase)) { //System.Diagnostics.Process.Start("explorer.exe", "file:///D:/"); System.Uri uri = new System.Uri(@"D:\temp\SQL\COR_Basic_Demo_V4_sts.bak"); if (System.Environment.OSVersion.Platform == System.PlatformID.Unix) { uri = new System.Uri(@"/root/Downloads/built-compare.zip"); } string fileUri = uri.AbsoluteUri; // turns a Uri back into a local filepath too for anyone that needs this. // string path = new System.Uri("file:///C:/whatever.txt").LocalPath; System.IO.FileAttributes attr = System.IO.File.GetAttributes(uri.LocalPath); if (attr.HasFlag(System.IO.FileAttributes.Directory)) { System.Console.WriteLine("Its a directory"); } else { System.Console.WriteLine("Its a file"); } if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX)) { // open -a Finder myTextFile.txt. using (System.Diagnostics.Process.Start("open", "-a Finder \"" + fileUri + "\"")) { } } else if (System.Environment.OSVersion.Platform == System.PlatformID.Unix) { // nautilus <path_to_file> // activate window // gnome-open PATH // open zip file in archiver // xdg-open file // open explorer window with file // nautilus filename // https://github.com/mono/dbus-sharp // https://developers.redhat.com/blog/2017/09/18/connecting-net-core-d-bus/ // https://unix.stackexchange.com/questions/202214/how-can-i-open-thunar-so-that-it-selects-specific-file // open -a Finder myTextFile.txt. try { using (System.Diagnostics.Process.Start("nautilus1", "\"" + fileUri + "\"")) { } } catch (System.Exception e) { System.Console.WriteLine(e); } } else { // explorer.exe /select,"C:\Folder\subfolder\file.txt" using (System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + fileUri + "\"")) { } } //if (context.WebSockets.IsWebSocketRequest) //{ // System.Net.WebSockets.WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); // await Echo(context, webSocket); //} //else //{ // context.Response.StatusCode = 400; //} } else { await next(); } }); } // End Sub UseOpenFolderOrFileExtensions(this Microsoft.AspNetCore.Builder.IApplicationBuilder app)
} // End Sub ConfigureServices // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( Microsoft.AspNetCore.Builder.IApplicationBuilder app , Microsoft.AspNetCore.Hosting.IWebHostEnvironment env , Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { // https://gunnarpeipman.com/aspnet-core-syslog/ // https://stackoverflow.com/questions/20951667/how-to-write-to-kiwi-syslog-server-log-c- // https://github.com/emertechie/SyslogNet/tree/master/SyslogNet.Client/Transport // https://maxbelkov.github.io/visualsyslog/ loggerFactory.AddSyslog("192.168.210.56", 514); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseDefaultFiles( new Microsoft.AspNetCore.Builder.DefaultFilesOptions() { DefaultFileNames = new System.Collections.Generic.List <string>() { "index.htm", "index.html" } } ); app.UseStaticFiles( new Microsoft.AspNetCore.Builder.StaticFileOptions() { ServeUnknownFileTypes = true, DefaultContentType = "application/octet-stream", ContentTypeProvider = new ExtensionContentTypeProvider(), OnPrepareResponse = delegate(Microsoft.AspNetCore.StaticFiles.StaticFileResponseContext context) { // https://stackoverflow.com/questions/49547/how-do-we-control-web-page-caching-across-all-browsers // The Cache-Control is per the HTTP 1.1 spec for clients and proxies // If you don't care about IE6, then you could omit Cache-Control: no-cache. // (some browsers observe no-store and some observe must-revalidate) context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0"; // Other Cache-Control parameters such as max-age are irrelevant // if the abovementioned Cache-Control parameters (no-cache,no-store,must-revalidate) are specified. // Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies. // In HTTP 1.1, the Cache-Control takes precedence over Expires, so it's after all for HTTP 1.0 proxies only. // If you don't care about HTTP 1.0 proxies, then you could omit Expires. context.Context.Response.Headers["Expires"] = "-1, 0, Tue, 01 Jan 1980 1:00:00 GMT"; // The Pragma is per the HTTP 1.0 spec for prehistoric clients, such as Java WebClient // If you don't care about IE6 nor HTTP 1.0 clients // (HTTP 1.1 was introduced 1997), then you could omit Pragma. context.Context.Response.Headers["pragma"] = "no-cache"; // On the other hand, if the server auto-includes a valid Date header, // then you could theoretically omit Cache-Control too and rely on Expires only. // Date: Wed, 24 Aug 2016 18:32:02 GMT // Expires: 0 // But that may fail if e.g. the end-user manipulates the operating system date // and the client software is relying on it. // https://stackoverflow.com/questions/21120882/the-date-time-format-used-in-http-headers } // End Sub OnPrepareResponse } ); app.UseRouting(); // https://stackoverflow.com/questions/60791843/changing-routedata-in-asp-net-core-3-1-in-middleware app.Use( async delegate(Microsoft.AspNetCore.Http.HttpContext context, System.Func <System.Threading.Tasks.Task> next) { string url = context.Request.Headers["HOST"]; string[] splittedUrl = url.Split('.'); if (splittedUrl != null && (splittedUrl.Length > 0)) { context.GetRouteData().Values.Add("Host", splittedUrl[0]); // context.GetRouteData().Values["controller"] = "test"; } // End if (splittedUrl != null && (splittedUrl.Length > 0)) // if (splittedUrl != null && (splittedUrl.Length > 0 && splittedUrl[0] == "admin")) // { // context.GetRouteData().Values.Add("area", "Admin"); // } // Call the next delegate/middleware in the pipeline await next(); } ); app.UseAuthorization(); /* * app.UseMvc( * delegate(IRouteBuilder routes) * { * routes.DefaultHandler = new Microsoft.AspNetCore.Mvc.Routing.AreaRouter(); * // routes.MapRoute(name: "areaRoute", template: "{controller=Home}/{action=Index}"); * } * ); */ // https://stackoverflow.com/questions/278668/is-it-possible-to-make-an-asp-net-mvc-route-based-on-a-subdomain // https://stackoverflow.com/questions/57172884/mapping-subdomains-to-areas-in-asp-net-core-3 app.UseEndpoints( delegate(Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints) { endpoints.MapDynamicControllerRoute <SearchValueTransformer>("search/{**product}"); // de.bar.int:5001/ endpoints.MapControllerRoute( name: "default", // pattern: "{controller=Home}/{action=Index}/{id?}", // pattern: "{controller=Blog}/{action=Index}/{id?}", pattern: "{controller=Blog}/{action=ShowEntry}/{id?}" ); } ); } // End Sub Configure