public void determine_request_culture_test() { // Arrange var req = new Mock <HttpRequest>(); req.Setup(x => x.Query) .Returns(new ReadableStringCollection(new Dictionary <string, StringValues> { { "lang", "zh" } })); var httpContext = new Mock <HttpContext>(); httpContext.Setup(x => x.Request) .Returns(req.Object); var accessor = new Mock <IHttpContextAccessor>(); accessor.Setup(x => x.HttpContext) .Returns(httpContext.Object); var queryStringProvider = new QueryStringRequestCultureProvider(accessor.Object); // Act var actual = queryStringProvider.DetermineRequestCulture(); // Assert Assert.Equal(new string[] { "zh" }, actual); }
public async void GetTheRightCultureInfoRegardlessOfCultureNameCasing() { using (var server = TestServer.Create(app => { var options = new RequestLocalizationOptions() { SupportedCultures = new List <CultureInfo> { new CultureInfo("FR") }, SupportedUICultures = new List <CultureInfo> { new CultureInfo("FR") } }; var provider = new QueryStringRequestCultureProvider(); provider.QueryStringKey = "c"; provider.UIQueryStringKey = "uic"; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options, defaultRequestCulture: new RequestCulture("en-US")); app.Run(context => { var requestCultureFeature = context.Features.Get <IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("fr", requestCulture.Culture.ToString()); Assert.Equal("fr", requestCulture.UICulture.ToString()); return(Task.FromResult(0)); }); })) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=FR&uic=FR"); } }
public async Task GetCultureInfoFromQueryStringWithCustomKeys() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List <CultureInfo> { new CultureInfo("ar-SA") }, SupportedUICultures = new List <CultureInfo> { new CultureInfo("ar-YE") } }; var provider = new QueryStringRequestCultureProvider(); provider.QueryStringKey = "c"; provider.UIQueryStringKey = "uic"; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get <IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); Assert.Equal("ar-YE", requestCulture.UICulture.Name); return(Task.FromResult(0)); }); }); }).Build(); await host.StartAsync(); using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=ar-SA&uic=ar-YE"); } }
public void determine_request_culture_with_empty_query_string_test() { // Arrange var req = new Mock<HttpRequest>(); req.Setup(x => x.Query) .Returns(new ReadableStringCollection(new Dictionary<string, StringValues>())); var httpContext = new Mock<HttpContext>(); httpContext.Setup(x => x.Request) .Returns(req.Object); var accessor = new Mock<IHttpContextAccessor>(); accessor.Setup(x => x.HttpContext) .Returns(httpContext.Object); var queryStringProvider = new QueryStringRequestCultureProvider(accessor.Object); // Act var actual = queryStringProvider.DetermineRequestCulture(); // Assert Assert.Equal(new string[] { }, actual); }
public async void GetCultureInfoFromQueryStringWithCustomKeys() { using (var server = TestServer.Create(app => { var options = new RequestLocalizationOptions(); var provider = new QueryStringRequestCultureProvider(); provider.QueryStringKey = "c"; provider.UIQueryStringKey = "uic"; options.RequestCultureProviders.Insert(0, provider); app.UseRequestLocalization(options); app.Run(context => { var requestCultureFeature = context.Features.Get <IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture; Assert.Equal("ar-SA", requestCulture.Culture.Name); Assert.Equal("ar-YE", requestCulture.UICulture.Name); return(Task.FromResult(0)); }); })) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=ar-SA&uic=ar-YE"); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerService logger) { #region Set Date Format IOptions <RequestLocalizationOptions> options = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >(); IList <IRequestCultureProvider> requestCultureProviderList = options.Value.RequestCultureProviders; CookieRequestCultureProvider cookieProvider = requestCultureProviderList.OfType <CookieRequestCultureProvider>().First(); QueryStringRequestCultureProvider urlProvider = requestCultureProviderList.OfType <QueryStringRequestCultureProvider>().First(); cookieProvider.Options.DefaultRequestCulture = new RequestCulture("en-US"); cookieProvider.Options.DefaultRequestCulture.Culture.DateTimeFormat.ShortDatePattern = "M/d/yyyy"; urlProvider.Options.DefaultRequestCulture = new RequestCulture("en-US"); urlProvider.Options.DefaultRequestCulture.Culture.DateTimeFormat.ShortDatePattern = "M/d/yyyy"; cookieProvider.CookieName = "UserCulture"; options.Value.RequestCultureProviders.Clear(); options.Value.RequestCultureProviders.Add(cookieProvider); options.Value.RequestCultureProviders.Add(urlProvider); app.UseRequestLocalization(options.Value); #endregion if (env.IsDevelopment()) { logger.DatabaseLogger.Error("In Development environment"); app.UseDeveloperExceptionPage(); //Built-in middleware } else { app.UseExceptionHandler("/Error"); } //The parameterless UseStaticFiles method overload marks the files in web root as servable. //following markup references wwwroot/images/banner1.svg: //<img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" /> app.UseStaticFiles(); // For the wwwroot folder /* * // Set up custom content types - associating file extension to MIME type * var provider = new FileExtensionContentTypeProvider(); * // Add new mappings * provider.Mappings[".myapp"] = "application/x-msdownload"; * provider.Mappings[".htm3"] = "text/html"; * provider.Mappings[".image"] = "image/png"; * // Replace an existing mapping * provider.Mappings[".rtf"] = "application/x-msdownload"; * // Remove MP4 videos. * provider.Mappings.Remove(".mp4"); * * app.UseStaticFiles(new StaticFileOptions { * FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")), * RequestPath = "/StaticFiles", * ContentTypeProvider = provider * }); * <img src="~/StaticFiles/images/banner1.svg" alt="ASP.NET" class="img-responsive" /> * * //Set HTTP response headers: A StaticFileOptions object can be used to set HTTP response headers. * //In addition to configuring static file serving from the web root, the following code sets the Cache-Control header: * string cachePeriod = env.IsDevelopment() ? "600" : "604800"; * app.UseStaticFiles(new StaticFileOptions * { * OnPrepareResponse = ctx => * { * // Requires: using Microsoft.AspNetCore.Http; * ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}"); * } * }); */ if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseRouting(); //app.UseCors("CorsPolicy"); /*url: https://docs.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-3.1 * Use Response Compression Middleware when you're: * 1-Unable to use the following server-based compression technologies: * IIS Dynamic Compression module * Apache mod_deflate module * Nginx Compression and Decompression * 2-Hosting directly on: * HTTP.sys server (formerly called WebListener) * Kestrel server */ app.UseResponseCompression(); //Response Caching Middleware only caches server responses that result in a 200 (OK) status code. app.UseResponseCaching(); app.Use(async(context, next) => { //Cache-Control � Caches cacheable responses for up to 10 seconds. context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue() { NoCache = true, NoStore = true, MaxAge = TimeSpan.FromSeconds(10) }; //Vary � Configures the middleware to serve a cached response only if the Accept-Encoding header of subsequent requests matches that of the original request. context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" }; await next(); }); /* * The primary difference between UseWhen and MapWhen is how later (i.e. registered below) middleware is executed. * Unlike MapWhen, UseWhen continues to execute later middleware regardless of whether the UseWhen predicate was true or false. */ app.UseWhen(httpContext => httpContext.Request.Path.Value.ToLower().StartsWith(@"/Proxy/proxy.ashx", StringComparison.OrdinalIgnoreCase), builder => builder.UseProxyServerMiddleware(app.ApplicationServices.GetService <IProxyConfigService>(), app.ApplicationServices.GetService <IProxyService>(), app.ApplicationServices.GetService <IMemoryCache>()) ); /* * The [ApiController] attribute makes attribute routing a requirement. * Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure. */ app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("DefaultWithActionApi", "api/{controller=Authenticate}/{action=Index}/{id?}"); endpoints.MapControllerRoute("DefaultDeleteApi", "api/{controller}/{id}", new { action = "Delete" }, new { id = @"\d+", httpMethod = new HttpMethodRouteConstraint(HttpMethod.Delete.ToString()) }); endpoints.MapControllerRoute("DefaultGetByIdApi", "api/{controller}/{id}", new { action = "GetByID" }, new { id = @"\d+", httpMethod = new HttpMethodRouteConstraint(HttpMethod.Get.ToString()) }); endpoints.MapControllerRoute("DefaultGetApi", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodRouteConstraint(HttpMethod.Get.ToString()) }); endpoints.MapControllerRoute("DefaultPostApi", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodRouteConstraint(HttpMethod.Post.ToString()) }); endpoints.MapControllerRoute("DefaultPutApi", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodRouteConstraint(HttpMethod.Put.ToString()) }); endpoints.MapHub <ChartHub>("/chart"); }); /* * For single page applications, the SPA middleware UseSpaStaticFiles usually comes last in the middleware pipeline. * The SPA middleware comes last: * - To allow all other middlewares to respond to matching requests first. * - To allow SPAs with client-side routing to run for all routes that are unrecognized by the server app. */ 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"; spa.Options.StartupTimeout = TimeSpan.FromSeconds(1000); /*see http://www.jiodev.com/aspnet/core/spa/angular * spa.UseSpaPrerendering(options => * { * options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.bundle.js"; * options.BootModuleBuilder = env.IsDevelopment() ? new AngularCliBuilder(npmScript: "build:ssr") : null; * options.ExcludeUrls = new[] { "/sockjs-node" }; * }); */ if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); }