Notes from building a first ASP.Net Core App (part 2)

  1. You can add any custom settings to an ASP.Net application that can be used in that Application.
  2. This is done by adding a configuration JSON file. Right-click to add a new file and add a JSON file from the menu (make sure you don’t mistake this for a TypeScript JSON file. They are different.) Call it mysettings.json.
  3. Add a new piece of JSON with a custom setting. My setting is as follows:
    {
    "my-custom-message": "The quick brown fox!"
    }
    
  4. To be able to process JSON configuration files, a nuget package is needed. Right-click on the References and select Manage Nuget Packages. Search for and Install the Microsoft.Extensions.Configuration.Json package, accepting the licence.
  5. Add the following snippet of code at the top of the Startup.cs file:
     public class Startup
     {
        public IConfiguration Configuration { get; set; }
    
        public Startup()
        {
             Configuration = new ConfigurationBuilder()
                               .SetBasePath(Directory.GetCurrentDirectory())
                               .AddJsonFile("mysettings.json")
                               .Build();
        }
    
    

    Note that if you don’t set the base path, it won’t know where to look for your configuration json file. You will also need to add a reference to the Directory object. (Highlight the Directory object and click Ctrl-Dot. Then click Enter to add the “using System.IO;” statement.)

  6. Adding the Nuget package made the AddJsonFile method discoverable. Otherwise you would get a red squiggly line under the AddJsonFile method and the code wouldn’t compile.
  7. Now in the Configure method, which displays the “Hello World!” text, change the app.Run statement to:
                app.Run(async (context) =>
                {
                    var myCustomMessage = Configuration["my-custom-message"];
                    var newHelloWorldMessage = string.Format("Hello World! Your text was >{0}<", myCustomMessage);
                    await context.Response.WriteAsync(newHelloWorldMessage);
                });
    
  8. Finally, compile and run your code (F5) and see the result. It should show:
    “Hello World! Your text was >The quick brown fox!<“

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: