【问题标题】:How to obtain the ASP.NET Core application name?如何获取 ASP.NET Core 应用程序名称?
【发布时间】:2017-12-30 10:06:59
【问题描述】:

我想在 ASP.NET Core 1.1 的页脚中显示

© 2017 MyApplication

<p>&copy; 2017 @(ApplicationName)</p>

如何获取应用程序名称?

我在这个主题上找到了an article,但它对PlatformServices.Default.Application.ApplicationName 感到困惑,因为它说不要使用Microsoft.Extensions.PlatformAbstractions,但没有说明应用程序名称应该使用什么...

【问题讨论】:

  • 与其将其绑定到程序集名称,我认为更好的解决方案是将您想要的确切文本简单地放在布局文件中。
  • @NateBarbettini 我想要的确切文本是项目属性中填写的应用程序名称。

标签: asp.net-core asp.net-core-1.1


【解决方案1】:

你可以试试:

@using System.Reflection;
<!DOCTYPE html>
<html>
 ....

    <footer>
        <p>&copy; 2017 - @Assembly.GetEntryAssembly().GetName().Name</p>
    </footer>
</html>

我不确定这是一个好方法,但它对我有用:)

【讨论】:

  • 应该有什么好办法,把应用名放在资源文件里?
  • 仅适用于应用程序名称,我更喜欢将您想要的确切文本放在布局文件中,因为应用程序名称不会经常更改。 :) 顺便说一句,开发人员直观地了解它在哪里。
【解决方案2】:

有很多方法可以实现它。这是我在项目中的做法。

我的项目名称通常与应用程序名称不同,应用程序名称可能包含空格或更长。因此,我将项目名称和版本号保留在 appsettings.json 文件中。

appsettings.json

{
  "AppSettings": {
    "Application": {
      "Name": "ASP.NET Core Active Directory Starter Kit",
      "Version": "2017.07.1"
    }
  }
}

Startup.cs

将设置从appsettings.json 文件加载到AppSettings POCO。然后它会自动在 DI 容器中注册为IOptions&lt;AppSettings&gt;

public void ConfigureServices(IServiceCollection services)
{
   services.AddOptions();
   services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

AppSettings.cs

注意:我还有一些其他设置,因此我将它们全部保存在 AppSettings POCO 中。

public class AppSettings
{
    public Application Application { get; set; }
}

public class Application
{
    public string Name { get; set; }
    public string Version { get; set; }
}

Usage (_layout.cshtml)

IOptions&lt;AppSettings&gt; 注入查看。 如果你愿意,你也可以将它注入到控制器中。

@inject IOptions<AppSettings> AppSettings

<footer class="main-footer">
   @AppSettings.Value.Application.Version
   @AppSettings.Value.Application.Name</strong>
</footer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多