0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET Core ローカリゼーションでハマる事

Posted at

View Localization

各Viewでのリソースと共有リソースを使う場合、どちらかのリソースが読み込めない

Program.cs (Startup.cs)

// MVC/Razor Pages
builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, option => { option.ResourcesPath = "Resources"; })

// localization
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

Views/Foo/Index.cshtml

@using System.Collections.Generic
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Localization
@inject IViewLocalizer Localizer
@inject IHtmlLocalizer<TaskManagerApp.SharedResource> SharedLocalizer

<p>@Localizer["foo"]</p>
<p>@SharedLocalizer["foo message"]</p>

SampleApp.Resources.Views.SharedResource.resx

foo message = なにかメッセージ

SampleApp.Resources.Views/Foo/Index.resx

foo = メッセージ

こうすると SharedResource が読み込めない。

解決

空のSampleApp.SharedResource.cs を追加する

namespace SampleApp{
  public class  SharedResource {}
}

原因

options => options.ResourcesPath = "Resources" を設定することでリソース検索パスが "SampleApp.Resources.Resources" になってしまうから。

DataAnnotationLocalizer

builder.Services.AddControllersWithViews(options => {
    options.ModelMetadataDetailsProviders.Add(new CustomValidationMetadataProvider(typeof(TaskManagerApp.Resources.ValidationMessage)));
})
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, option => { option.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization(options => { 
        options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SampleApp.Resources.DataAnnotationText));
    });

これも前述と同じで SampleApp.Resources.Resources.DataAnnotationText が検索されてしまうので空の SampleApp.DataAnnotationText クラスを追加する。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?