简体   繁体   English

请求的 QueryString 本地化区域性在 ASP.NET 核心 Razor 页面模型中不起作用 AJAX 请求

[英]Requested QueryString localized culture is not working in ASP.NET Core Razor Page models with AJAX Request

We are getting an strange behavior in multi-language development in ASP.NET Core Razor pages based application, IStringLocalizer object that we are using in.cshtml pages is recognizing the currently selected culture and translating all elements correctly those are on.cshtml file as per selected culture's resource files, but same object used inside page models (ie .cshtml.cs) files, is always translating into browser default language when requested through AJAX GET or POST method .我们在 ASP.NET Core Razor 基于页面的应用程序,IStringLocalizer ZA8CFDE6331BD59EB2AC96F8911B59EB2AC96F8911C4B666Z 中的多语言开发中遇到了一个奇怪的行为,我们正在使用 in.cshtml 页面正确地识别所有当前选择的文化,并将这些文化识别为当前选定的文化。资源文件,但在页面模型(即 .cshtml.cs)文件中使用的相同 object 在通过 AJAX GET 或 POST 方法请求时始终转换为浏览器默认语言。 Its not able to recognize currently selected culture.它无法识别当前选择的文化。 Used QueryStringRequestCultureProvider.使用了 QueryStringRequestCultureProvider。

This is what working in.cshtml page and its translating as per the culture selected in String这就是在.cshtml 页面中工作的内容,并根据字符串中选择的文化对其进行翻译

@page
@inject IStringLocalizer<IndexModel> localizer  
@model IndexModel
@{
    ViewData["Title"] = "Home page";
    var requestCultureFeature = HttpContext.Features.Get<IRequestCultureFeature>();
    var requestCulture = requestCultureFeature.RequestCulture;
}     
<div class="text-center">
    <h1 class="display-4">@localizer["Welcome"]</h1>        
</div>

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"></script>
<script lang="javascript">
    $(document).ready(function () {

        $("#btnnsubmit").click(function () {
            var obj = {};
            obj.name = "name";

            //url
            $.ajax({
                type: "Get",
                url: '/Index?handler=callingAjax',
                data: obj,
                dataType: "html",
                contentType: "application/json; charset=utf-8",
                success: function () {
                    debugger;

                },
                error: function () {

                }
            });
        });
    });

</script>

This is what I have done in page models (ie in.cshtml.cs pages) and it always translating into browser's default language.这就是我在页面模型(即 in.cshtml.cs 页面)中所做的,它总是翻译成浏览器的默认语言。

    public class IndexModel : PageModel
    {
        public string Message { get; set; }

        private readonly ILogger log;

        private readonly IStringLocalizer<IndexModel> localizer;

        public IndexModel(ILogger<IndexModel> log, IStringLocalizer<IndexModel> _localizer)
        {
            this.log = log;
            localizer = _localizer;
        }

         public void OnGet()
         {
        // Called on page load without AJAX
        //Localization is working here, gives translation based on selected 
          //language 
            string str = _localizer["InvalidLoginAttempt"];
         }

    public IActionResult OnGetCallingAjax()
    {  
        int MaxThreads = 1;
        // Called using AJAX
        //Localization is not working here, always gives translation based on 
          //browsers default language, 
        string str1 = _localizer["InvalidLoginAttempt"];

        string message = "SUCCESS";
        return new JsonResult(new
        {
            Error = false,
            Message = message,
            // lstlang = lstlanguage
        });
    }
  }

Below are the Startup file setting.下面是启动文件设置。

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                 {
                    new CultureInfo("de"),
                    new CultureInfo("fr"),
                    new CultureInfo("en"),
                    new CultureInfo("nl"),
                 };
                options.DefaultRequestCulture = new RequestCulture("de");               
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;  
                options.RequestCultureProviders = new List<IRequestCultureProvider>
                {
                  new QueryStringRequestCultureProvider(),
                  new CookieRequestCultureProvider()
                };
            });

            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
            });

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });            

            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30); //default is 20 min
            });

            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMemoryCache();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
        }

        // 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.AddLog4Net();
            Log4NetFilters.Set(               // filter out the standard log messages with source "Microsoft"
              source: "Microsoft",
              filteredLogLevel: LogLevel.Information);

            ILogger logger = loggerFactory.CreateLogger<Program>();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseStaticFiles();
            //app.UseRouting();
            app.UseSession();
            app.UseCookiePolicy();
            app.UseHttpsRedirection();

            var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
            app.UseRequestLocalization(localizationOptions);

            app.UseMvc();
        }

From the comments, seems that the issue is that you were just providing the culture in the query string of the initial request and not storing it anywhere, hence the culture isn't used in posterior requests, AJAX ones included.从评论来看,问题似乎在于您只是在初始请求的查询字符串中提供了文化,而没有将其存储在任何地方,因此该文化不用于后面的请求,包括 AJAX 请求。

Putting the culture in the query string everywhere works, but it's probably not ideal.将文化放在查询字符串中的任何地方都有效,但这可能并不理想。

In your Startup , you're setting up CookieRequestCultureProvider , so you can make use of that instead of putting things in the query string every time.在您的Startup中,您正在设置CookieRequestCultureProvider ,因此您可以利用它而不是每次都将内容放入查询字符串中。

As an example, you could create an action that can be invoked to store the culture preferences in a cookie:例如,您可以创建一个可以调用以将文化偏好存储在 cookie 中的操作:

public class CultureController : Controller
{
    [HttpPost]
    public IActionResult SelectCulture(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );

        return LocalRedirect(returnUrl);
    }
}

Doing this, the CookieRequestCultureProvider would pick up the user preference.这样做, CookieRequestCultureProvider将获取用户偏好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 示例 AJAX 回调到 ASP.NET Core Razor 页面 - Example AJAX call back to an ASP.NET Core Razor Page ASP.NET表单身份验证默认重定向[有效]和带有QueryString的重定向到请求的页面[无效] - ASP.NET Forms Authentication Default Redirect [Working] and Redirect to Requested Page w/QueryString [Not Working] Asp.net 核心 Razor 页面,页面处理程序不工作 - Asp.net Core Razor Pages, page handler not working 具有日期文化问题的Asp.Net Core Api请求 - Asp.Net Core Api Request with Date Culture Issue 为什么 PartialView 模型在 PostBack 到 Asp.Net Core Razor 主页视图的控制器中为空? - Why are the PartialView models null in a PostBack to an Asp.Net Core Razor main page view's controller? 在一个 razor 视图中创建多个模型(ASP.NET Core) - Multiple create models in one razor view (ASP.NET Core) ASP.NET Core:为所有模型生成 Razor 页面 - ASP.NET Core : Generate Razor Pages for all models Asp.Net Core Razor Pages Failed AJAX request after migration to Version 3.1 - Asp.Net Core Razor Pages Failed AJAX request after migrating to Version 3.1 Ajax请求不适用于ASP.NET页面方法 - Ajax request is not working with ASP.NET page method 如何在asp.net核心剃须刀页面2.2中设置日期格式和区域性 - How to set date formats and culture in asp.net core razor pages 2.2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM