How to obtain the ASP.NET Core application name?
Asked Answered
E

2

6

I would like do display in the footer of an ASP.NET Core 1.1

© 2017 MyApplication

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

How do I get the application name?

I found an article on this subject but it's confusing about PlatformServices.Default.Application.ApplicationName, because it says do not use Microsoft.Extensions.PlatformAbstractions, but does not say what to use instead for the application name...

Esse answered 24/7, 2017 at 17:56 Comment(2)
Rather than tying it to the assembly name, I think a better solution would be to simply put the exact text you want in the layout file.Addlepated
@NateBarbettini The exact text I want is the application name as filled in the project properties.Esse
B
12

You could try:

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

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

I am not sure it is a good way, but it works for me :)

enter image description here

Bendix answered 25/7, 2017 at 5:8 Comment(2)
what should be the good way, put the application name in resource files?Esse
for application name only , I prefer to put exact text you want in layout file because application name is not changed frequently. :) btw, developer intuitively understand where it is.Bendix
C
6

There are a lot of way to achieve it. Here is how I do in my projects.

I normally have project name different from application name which could have spaces or much longer. So, I Keep the project name and version number in appsettings.json file.

appsettings.json

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

Startup.cs

Load setting from appsettings.json file into AppSettings POCO. It then automatically register in DI container as IOptions<AppSettings>.

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

AppSettings.cs

Note: I have some other settings so that I keep them all together inside 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)

Inject IOptions<AppSettings> to View. You can also inject it to controller if you would like.

@inject IOptions<AppSettings> AppSettings

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

enter image description here

Camm answered 25/7, 2017 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.