перейти с .netcore1.1 на .netcore2.2, локализация не работает - PullRequest
0 голосов
/ 24 января 2019

это мой startup.cs:

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
                .AddViewLocalization()
                .AddDataAnnotationsLocalization()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddMvcOptions(options =>
                {
                    // Don't combine authorize filters (keep 2.0 behavior).
                    options.AllowCombiningAuthorizeFilters = false;
                    // All exceptions thrown by an IInputFormatter are treated
                    // as model state errors (keep 2.0 behavior).
                    options.InputFormatterExceptionPolicy = InputFormatterExceptionPolicy.AllExceptions;
                }); ;

        var sessionProvider = Configuration["Session:Provider"];

        if (sessionProvider == "redis")
        {
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = Configuration["Session:Configuration"];
                options.InstanceName = Configuration["Session:InstanceName"];
            });
        }
        else
        {
            services.AddDistributedMemoryCache();
        }

        services.AddSession();

        // Language filter
        services.AddScoped<LanguageActionFilter>();

        // Captcha generator
        services.AddSingleton<ICaptchaGenerator, CaptchaGenerator>();

        // account verification service
        services.Configure<RoboCloudClientService.Options>(Configuration.GetSection("RoboCloud"));
        services.AddSingleton<IAccountVerificationService, RoboCloudClientService>()
                .AddSingleton<IBlobStoreTokenService, RoboCloudClientService>();

        // download database
        var downloadDatabaseType = Configuration["Download:DatabaseType"];
        var downloadDatabaseConnectionString = Configuration["Download:DatabaseConnectionString"];

        if (downloadDatabaseType == "npgsql")
            services.AddDbContext<Websites.Download.Data.Models.DatabaseContext>(options => options.UseNpgsql(downloadDatabaseConnectionString));
        else if (downloadDatabaseType == "sqlserver")
            services.AddDbContext<Websites.Download.Data.Models.DatabaseContext>(options => options.UseSqlServer(downloadDatabaseConnectionString));
        else
            throw new Exception($"Unsupported database type {downloadDatabaseType}");

        // download services
        services.Configure<QiniuDownloadStoreService.Options>(options =>
        {
            options.DownloadBaseUrl = Configuration["Download:QiniuDownloadBaseUrl"];
            options.UploadBaseUrl = Configuration["Download:QiniuUploadBaseUrl"];
        });

        services.Configure<DownloadSiteService.Options>(options =>
        {
            options.DownloadSiteBaseUrl = Configuration["Download:DownloadSiteBaseUrl"];
            options.SingleSiteDeployment = Configuration.GetValue<bool>("Download:SingleSiteDeployment");
        });

        services.AddQiniuDownloadStoreService()
                .AddOfficialWebsiteEntityServices()
                .AddScoped<IDownloadSiteService, DownloadSiteService>();

        services.AddSingleton<ILocalizationService, LocalizationService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,  Websites.Download.Data.Models.DatabaseContext downloadContext, ILocalizationService localizationService)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        var supportedCultures = new[]
        {
            new CultureInfo("en"),
            new CultureInfo("zh-cn"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("zh-cn"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

        app.UseHttpsRedirection();
        app.UseCookiePolicy();

        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{culture=unknown}/{controller=Home}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "fallback",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        var provider = new FileExtensionContentTypeProvider();
        provider.Mappings[".7z"] = "application/x-7z-compressed";
        provider.Mappings[".hex"] = "application/octet-stream";
        provider.Mappings[".bz2"] = "application/x-bzip2-compressed";
        provider.Mappings[".gz"] = "application/x-gz-compressed";

        app.UseStaticFiles(new StaticFileOptions()
        {
            ContentTypeProvider = provider
        });

        localizationService
            .AddJsonFile("en", $"{ env.ContentRootPath }/lang.en.json", isDefault: true)
            .AddJsonFile("cn", $"{ env.ContentRootPath }/lang.cn.json");

        // database
        Websites.Download.Data.Models.DbInitializer.InitializeAsync(downloadContext).Wait();
    }
}

ниже - LanguageActionFilter:

public class LanguageActionFilter : ActionFilterAttribute
{
    private readonly ILogger _logger;

    public LanguageActionFilter(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger("Slamtec.Website.Services.LanguageActionFilter");
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.HttpContext.Request.Path == "/baidu_verify_oN9BP6xKw5.html")
        {
            context.Result = new FileContentResult(Encoding.UTF8.GetBytes("oN9BP6xKw5"), "text/html");
            return;
        }

        var culture = context.RouteData.Values["culture"]?.ToString() ?? "unknown";

        if (culture != "cn" && culture != "en")
        {
            var guessCulture = "en";

            if (context.HttpContext.Request.Headers.ContainsKey("Accept-Language"))
            {
                var acceptLanguages = context.HttpContext.Request.Headers["Accept-Language"];

                foreach (var acceptLanguageSet in acceptLanguages)
                {
                    foreach (var acceptLanguage in acceptLanguageSet.Split(';'))
                    {
                        if (acceptLanguage.Contains("en"))
                        {
                            guessCulture = "en";
                            break;
                        }
                        else if (acceptLanguage.Contains("zh"))
                        {
                            guessCulture = "cn";
                            break;
                        }
                    }
                }
            }

            if (context.HttpContext.Request.QueryString.HasValue)
                context.Result = new RedirectResult($"/{guessCulture}{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString.Value}");
            else
                context.Result = new RedirectResult($"/{guessCulture}{context.HttpContext.Request.Path}");

            return;
        }

        _logger.LogInformation($"Setting the culture from the URL: {culture}");

        base.OnActionExecuting(context);
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result != null && context.Result is ViewResult)
        {
            var view = context.Result as ViewResult;
            view.ViewData["LanguageCode"] = context.RouteData.Values["culture"].ToString();
        }

        base.OnActionExecuted(context);
    }
}

если я меняю .SetCompatibilityVersion (CompatibilityVersion.Version_2_2) на .SetCompatibilityVersion (CompatibilityVersion.Version_2_1), он работает.

Но если я использую CompatibilityVersion.Version_2_2, это не сработает Теперь проблема в том, когда я хочу перейти с домашней страницы на другую страницу, там будет неизвестный раунд. например: https://localhost:44390/cn/unknown/Home/Buy

Пожалуйста, помогите мне, спасибо.

С уважением.

...