asp.net - 没有注册 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' 类型的服务

标签 asp.net asp.net-mvc-4 localization asp.net-core globalization

我尝试使用 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>();
}

在我的 _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

错误:
An unhandled exception occurred while processing the request.

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' has been registered.

最佳答案

将类型添加到 IHtmlLocalizer like the docs demonstrate.

@inject IHtmlLocalizer<MyType> MyTypeLocalizer

另外,我注意到你还没有注册 ViewLocalization服务。您可能也需要这样做。
public void ConfigureServices(IServiceCollection services)
{
    services
       .AddLocalization(options => options.ResourcesPath = "Resources");

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

    ...

关于asp.net - 没有注册 'Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer' 类型的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286575/

相关文章:

asp.net - 我应该在 Page 对象的何处实现功能 - 构造函数或 OnPreInit?

c# - asp.net 从 List<> 方法获取值

jquery - 如何使用 jQuery 从 ASP.NET 代码后面调用非静态方法

jquery - 使用 jQuery 进行本地化

asp.net - 文化 - ASP.NET MVC 3 应用程序

javascript - 为什么 HTTP 图像没有出现在 HTTPS 应用程序中?

c# - 把加载放在邮件发送中

c# - 以编程方式访问 ASP.NET MVC4 上的文件

javascript - 在 MVC javascript 部分解析 @?

typescript - RequireJS + Bootstrap 日期选择器 + 区域设置文件