没有为"Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer"类型的服务注册

Yan*_*Btd 10 asp.net globalization localization asp.net-mvc-4 asp.net-core

我尝试使用ASP.Core来建立一个多语言网站.所以,我有我的StartUp.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization();
    services.Configure<RequestLocalizationOptions>(
    opts =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("de-DE"),
            new CultureInfo("de"),
            new CultureInfo("fr-FR"),
            new CultureInfo("fr"),
        };
        opts.DefaultRequestCulture = new RequestCulture("fr-FR");
        // Formatting numbers, dates, etc.
        opts.SupportedCultures = supportedCultures;
        // UI strings that we have localized.
        opts.SupportedUICultures = supportedCultures;
    });
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    services.AddMvc();
    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}
Run Code Online (Sandbox Code Playgroud)

在我的_ViewImports.cs中我有:

@using System.Threading.Tasks
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IHtmlLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Run Code Online (Sandbox Code Playgroud)

错误:

An unhandled exception occurred while processing the request.

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' has been registered.
Run Code Online (Sandbox Code Playgroud)

Sha*_*tin 13

像文档演示一样向IHtmlLocalizer添加类型.

@inject IHtmlLocalizer<MyType> MyTypeLocalizer
Run Code Online (Sandbox Code Playgroud)

另外,我注意到您尚未注册该ViewLocalization服务.您可能也需要这样做.

public void ConfigureServices(IServiceCollection services)
{
    services
       .AddLocalization(options => options.ResourcesPath = "Resources");

    services
      .AddMvc()
      .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix;

    ...
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,services.AddMvc().AddViewLocalization()帮助. (3认同)
  • AddMvcLocalization() 使用 MvcLocalizationServices.AddMvcLocalizationServices。这是注册 IHtmlLocalizer&lt;&gt; 和 IViewLocalizer (2认同)