Saturday, July 27, 2019

Launch Settings in ASP.NET Core WebAPI

Asp.Net core applications contain a new settings file called launchSettings.json, this file is under the Properties menu. The file contains the settings for running the application in different environments.

By default an Asp.Net Core Web API project contains 2 settings. First one for running under IIS Express and the 2nd settings for running in command line.

  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "HelloWebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }

There are 2 important properties in the above profile settings, first is the launchUrl, this setting decides the startup up Controller / Action method to be executed when the project is run, we can alter this path as required to execute a specific Controller / Action when the project is run.

 The 2nd important property is the environmentVariables, ASP.NET Core reads the environment variable ASPNETCORE_ENVIRONMENT at app startup and stores the value in IHostingEnvironment.EnvironmentName and is available in the startup configuration. We can use this to dynamically alter the behavior of the application based on the environment.

In the below Configure function we check if the Environment is Development if do we will show the Developer exception page with detailed error message, in other environments we redirect the user to a custom Error page.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Apart from the ASPNETCORE_ENVIRONMENT property we can add any custom properties under the environmentVariables section and use it across the application.


Search Flipkart Products:
Flipkart.com