Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Asp.net Core 2.0中的本地化不起作用_C#_Asp.net_Asp.net Mvc_Asp.net Core - Fatal编程技术网

C# Asp.net Core 2.0中的本地化不起作用

C# Asp.net Core 2.0中的本地化不起作用,c#,asp.net,asp.net-mvc,asp.net-core,C#,Asp.net,Asp.net Mvc,Asp.net Core,我添加了如下本地化。但是,它不会显示相关的值 public IServiceProvider ConfigureServices(IServiceCollection services) { // Add swagger here using extension methods. services.AddSwaggerService(); // Add language support here. // Default language is English. Supporte

我添加了如下本地化。但是,它不会显示相关的值

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 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];
}
}
公共类LOC服务
{
专用只读IStringLocalizer\u localizer;
/// 
///初始化类的新实例。
/// 
///工厂。
公共场所服务(IStringLocalizerFactory)
{
变量类型=类型(SharedResource);
var assemblyName=新的assemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer=factory.Create(“SharedResource”,assemblyName.Name);
}
/// 
///返回键的本地化字符串。
/// 
///钥匙。
///本地化字符串。
公共本地化字符串GetLocalizedHtmlString(字符串键)
{
返回_定位器[键];
}
}
控制员:

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;
}
公共类AuthController:ControllerBase
{
专用只读IStringLocalizer\u localizer;
公共授权控制器(IStringLocalizer localizer)
{
_定位器=定位器;
}
公共异步任务发布([FromBody]登录模型登录)
{     
if(wait_userService.IsUserAuthenticatedAsync(login.UserName,login.Password))
{
responseToken=wait_userService.GetResponseToken(login.UserName);
statusCode=HttpStatusCode.OK;
tokenResponseMessage=新的ResponseMessage(true、responseToken、新消息(statusCode));
//生成访问令牌
响应=Ok(令牌响应消息);
}
其他的
{
statusCode=HttpStatusCode.未经授权;
tokenResponseMessage=new ResponseMessage(假、空、新消息(状态码、,
_定位器[“登录\不正确的用户名密码]);
响应=未授权(令牌响应消息);
}
}
返回响应;
}

_localizer[“Login\u incorrecutsernamepassword”])会大摇大摆地返回Login\u incorrecutsernamepassword。

您可以随时进入文件夹
YourProject\obj\Debug\netcoreapp2.1
查看资源文件(例如,
MyProjectName.Resources.SharedResource.en.resource

检查
\u localizer[“Login\u incorrecturesernamepassword”]
的结果,以查找其
SearchedLocation
的值。它应该与资源文件的文件名匹配

在我的例子中,
SharedResource.cs
具有类似于
名称空间MyProjectName.Resources
的名称空间,而不是
名称空间MyProjectName
,这会导致错误的
SearchedLocation
-
MyProjectName.Resources.Resources.SharedResource

services.AddLocalization(options => options.ResourcesPath = "Resources");
将其名称空间更改为下面的名称空间,它将正常工作:

namespace MyProjectName
{
    public class SharedResource
    {
    }
}

如果您使用的是默认索引器,就像您在代码示例中所做的那样,那么据我所知,IStringLocalizer通过使用.NET framework的ResourceManager来查找与当前区域性匹配的字符串的本地化版本。这意味着,您需要实际使用默认区域性中Login\u incorrecutsernamepassword输出的字符串,而不是键
Login\u incorrecutsernamepassword
<代码>无效登录尝试。例如。如果您想改为使用密钥,请使用IStringLocalizer的GetString()方法并传入密钥
Login\u incorrectionSerNamePassword
services.AddLocalization(options => options.ResourcesPath = "Resources");
namespace MyProjectName
{
    public class SharedResource
    {
    }
}