簡體   English   中英

Asp.net Core 2.0中的本地化無法正常工作

[英]Localisation in Asp.net Core 2.0 not working

我添加了如下的本地化。 但是,它不顯示相關值。

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  // Add swagger here using extension methods.
  services.AddSwaggerService();

  // Add language support here.
  // Default language is English. Supported
  // languages are English and French.
  services.AddLanguageSupport();

  // Add controller
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                    .AddViewLocalization()
                    .AddDataAnnotationsLocalization(options =>
                    {
                      options.DataAnnotationLocalizerProvider = (type, factory) =>
                      {
                        var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                        return factory.Create("SharedResource", assemblyName.Name);
                      };
                      })
                    .AddControllersAsServices();
}

語言支持的擴展方法:

public static void AddLanguageSupport(this IServiceCollection services)
{
  // Add list of supported cultures
  // here. Two languages are English
  // and french.
  services.AddLocalization(options => options.ResourcesPath = "Resources");

  services.Configure<RequestLocalizationOptions>(
      options =>
      {
        var supportedCultures = new List<CultureInfo>
              {
                        new CultureInfo("en"),
                        new CultureInfo("fr"),
              };

        options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
      });
}

中間件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
  app.UseRequestLocalization(locOptions.Value);
}

在此處輸入圖片說明

在資源文件夾中,我具有以下內容:

SharedResource類:

public class SharedResource
{
}

LocService類:

public class LocService
{
private readonly IStringLocalizer _localizer;

/// <summary>
/// Initializes a new instance of the <see cref="LocService"/> class.
/// </summary>
/// <param name="factory">factory.</param>
public LocService(IStringLocalizerFactory factory)
{
  var type = typeof(SharedResource);
  var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
  _localizer = factory.Create("SharedResource", assemblyName.Name);
}

/// <summary>
/// returns localised string for a key.
/// </summary>
/// <param name="key">key.</param>
/// <returns>localised string.</returns>
public LocalizedString GetLocalizedHtmlString(string key)
{
  return _localizer[key];
}
}

控制器:

public class AuthController : ControllerBase
{
private readonly IStringLocalizer<SharedResource> _localizer;

public AuthController(IStringLocalizer<SharedResource> localizer)
{
  _localizer = localizer;
}

public async Task<ActionResult> Post([FromBody] LoginModel login)
{     
    if (await _userService.IsUserAuthenticatedAsync(login.UserName, login.Password))
    {
      responseToken = await _userService.GetResponseToken(login.UserName);

      statusCode = HttpStatusCode.OK;

      tokenResponseMessage = new ResponseMessage(true, responseToken, new Message(statusCode));

      // generate access token
      response = Ok(tokenResponseMessage);
    }
    else
    {
      statusCode = HttpStatusCode.Unauthorized;
      tokenResponseMessage = new ResponseMessage(false, null, new Message(statusCode, 
      _localizer["Login_InCorrectUserNamePassword"]));

      response = Unauthorized(tokenResponseMessage);
    }
  }

  return response;
}

_localizer [“ Login_InCorrectUserNamePassword”]))以Swagger返回Login_InCorrectUserNamePassword。

您總是可以進入文件夾YourProject\\obj\\Debug\\netcoreapp2.1來查看您的資源文件(例如, MyProjectName.Resources.SharedResource.en.resource )。

檢查的結果_localizer["Login_InCorrectUserNamePassword"]找到它的價值SearchedLocation 。它應該匹配的資源文件的文件名。

在我的情況下, SharedResource.cs有這樣一個命名空間namespace MyProjectName.Resources而不是namespace MyProjectName從而導致錯誤的SearchedLocation - MyProjectName.Resources.Resources.SharedResource ,因為我已經使用

services.AddLocalization(options => options.ResourcesPath = "Resources");

將其命名空間更改為以下名稱,即可使用:

namespace MyProjectName
{
    public class SharedResource
    {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM