如何在没有 assemblyinfo.cs 的情况下将 RootNamespace 属性添加到项目以修复本地化?

How to add RootNamespace attribute to project without assemblyinfo.cs to fix localization?

我有一个具有以下属性的 asp.net 核心项目:

我正在尝试使用 asp.net 本地化,但资源管理器找不到语言资源。 文档提供了一些答案:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-5.0#rootnamespaceattribute

If the root namespace of an assembly is different than the assembly name:

  • Localization does not work by default.
  • Localization fails due to the way resources are searched for within the assembly. RootNamespace is a build-time value which is not available to the executing process. If the RootNamespace is different from the AssemblyName, include the following in AssemblyInfo.cs (with parameter values replaced with the actual values):
using System.Reflection;
using Microsoft.Extensions.Localization;

[assembly: ResourceLocation("Resource Folder Name")]
[assembly: RootNamespace("App Root Namespace")]

问题是在 .net core 5 中不再有 assemblyInfo.cs 文件,而是自动生成的。这意味着我需要以某种方式将 RootNamespace 添加到 .csproj 文件。

我该怎么做?

编辑 我试过添加:

    <ItemGroup>
        <AssemblyMetadata Include="ResourceLocation" Value="Resources" />
        <AssemblyMetadata Include="RootNamespace" Value="Cmp.WebApi" />
    </ItemGroup>

到 .csproj 文件,但这没有用 - 它在 obj

中生成了以下 assemblyInfo
[assembly: System.Reflection.AssemblyMetadata("ResourceLocation", "Resources")]
[assembly: System.Reflection.AssemblyMetadata("RootNamespace", "OPG.WebApi")]

另请注意,如果 RootNameSpace 与程序集名称相同,则此方法工作正常。

编辑 2

我也试过:

    <PropertyGroup>
        <AssemblyResourceLocation>Resources</AssemblyResourceLocation>
        <AssemblyRootNamespace>Cmp.WebApi</AssemblyRootNamespace>
    </PropertyGroup>

但这也不起作用,考虑到我在 msbuild 任务中没有看到这些属性,这似乎合乎逻辑:

https://github.com/dotnet/sdk/blob/main/src/Tasks/Microsoft.NET.Build.Tasks/targets/Microsoft.NET.GenerateAssemblyInfo.targets

一个选项(也是我找到的唯一选项)是添加一个相当空的 AssemblyInfo.cs

using System.Runtime.InteropServices;
using Microsoft.Extensions.Localization;

// In SDK-style projects such as this one, several assembly attributes that were historically
// defined in this file are now automatically added during build and populated with
// values defined in project properties. For details of which attributes are included
// and how to customise this process see: https://aka.ms/assembly-info-properties


// Setting ComVisible to false makes the types in this assembly not visible to COM
// components.  If you need to access a type in this assembly from COM, set the ComVisible
// attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM.

[assembly: Guid("677ac300-e567-46dd-9281-cafe8d644224")]

[assembly: ResourceLocation("Resources")]
[assembly: RootNamespace("Cmp.WebApi")]

您只需选择 properties 文件夹,右键单击打开上下文菜单,然后选择 add > new item...,然后选择 AssemblyInfo.cs 模板即可:

这是在 asp.net 核心 5 项目中。