首页 > 解决方案 > 模型验证多语言翻译在 .net 核心中不起作用

问题描述

我正在开发多语言 .net core 2.1,因为我的模型项目不同,我的模型数据注释验证没有翻译成荷兰语。

当我使用 web 项目中的模型时,它可以工作。

所以我的问题是如何翻译来自不同模型项目的模型数据注释验证。

我的项目结构如下。

在此处输入图像描述

启动.cs

 services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });



        services.AddMvc()
            .AddViewLocalization(
                LanguageViewLocationExpanderFormat.Suffix,
                opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization();

        services.Configure<RequestLocalizationOptions>(
      opts =>
      {
          var supportedCultures = new List<CultureInfo>
      {
            new CultureInfo("en-GB"),
            new CultureInfo("nl-NL"),
      };

          opts.DefaultRequestCulture = new RequestCulture("nl-NL");
          // Formatting numbers, dates, etc.
          opts.SupportedCultures = supportedCultures;
          // UI strings that we have localized.
          opts.SupportedUICultures = supportedCultures;
      });

        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;
        });

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {


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

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "uploads")),
            RequestPath = "/uploads"
        });
        app.UseCookiePolicy();
        app.UseSession();
        app.UseMvc();

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

我如何翻译模型数据注释验证。提前致谢

标签: c#visual-studioasp.net-core-mvcmultilingualasp.net-core-2.1

解决方案


如果您想翻译模型数据注释验证和您的模型类库项目不同(模型类文件不是 Web 项目的一部分),那么您需要在模型类库项目中创建相同的“资源”文件夹。


推荐阅读