Setup and Configure ASP.NET Core Web API application

In this article, i am going to cover on how to setup ASP.NET Core application (MVC, Web API, Blazor) using .NET Core.

ASP.NET Core is Microsoft’s web development platform for processing HTTP Requests, and a series of principal frameworks for creating applications, utility frameworks that provide supporting features, see the illustrated picture below.

To be able to develop good applications, we need to understand how to configure our applications and its services.

Configuring .NET Core application is little different than a .NET Framework projects, There is no default Web.config file, instead it uses a build-in configuration framework that is build into the .NET Core.

1.1 Create a New Project:

Open Visual Studio and create a new ASP.NET Core Web Application:

Let’s choose a name and location of your project and click Next:

below choose a .NET core and ASP.NET Core 3.1 from the dropdown list, click the Create button and the project will start initializing:

1.2 launchSettings.json file Configuration:

This configuration file defines the launch behavior of the ASP.NET Core application, as you can see below, it has configuration for both IIS and self-hosted applications (kestrel). Let’s change launchBrowser property to false, to prevent the web browser from launching on application start.

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:64111",
      "sslPort": 44366
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": false,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CustomerOrders": {
      "commandName": "Project",
      "launchBrowser": false,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

we are developing a Web API project and we don’t really need a browser to check our API, so we will use Postman for this. Few other properties you need to understand are, applicationUrl, one for HTTP and one for HTTPS. launchUrl property determines which URL will the application navigate to initially.

Note: this HTTPS configuration is only valid in the local environment, you have to configure a valid certificate and HTTPS redirection once you deploy the application.

1.3 Program.cs and Startup.cs Explanations:

Program.cs: you configure the infrastructure of your application, such as the HTTP server, integration with IIS, logging, and configuration sources [loads configuration settings at runtime, such as connection strings, etc.]

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

CreateHostBuilder(args) method encapsulates all the stuff and makes this code more readable and keeps all the magic present but you can configure if you want to. After that we can call webBuilder.useStartup<Startup>() to initialize the Startup class.

Startup.cs:

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method is used to correctly create classes at runtime, 
       // dependencies are registered  with a container (IServiceCollection) in 
       // the ConfigureServices method.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(); 
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // Configure the middleware pipeline for handling HTTP requests.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

In the Configure method, we are going to add different middle ware components to the application’s request pipeline. For larger applications containing a lot of different services end up clutter code in ConfigureServices() method, so to make it more readable for the developers, we can structure the code into logical blocks as extension methods.

1.4 Extension Methods:

An Extension method is inherently as static method. what makes it different form other static methods is that , it accepts this as the first parameter, this represents the data type of the object which will be using that extension method.

let’s start writing some code, create a new folder Extensions in the project , and create a new static class in that folder names ServiceExtensions.

this new extension method configures CORS(Corss-Origin Resource Sharing) in our application, it is a mechanism to give or restrict access rights to applications from different domains.

 public static class ServiceExtensions
    {
        public static void ConfigureCors(this IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                      builder.AllowAnyOrigin() // allows requests from any source
                      .AllowAnyMethod() //allows all HTTP methods
                      .AllowAnyHeader()); // allow "accept","content-type"
            });
        }
    }

IIS Configuration:

ASP.NET Core applications are default self hosted, suppose if you want to host application on IIS, we need to configure an IIS integration to deployment to IIS. To do that, we need to add another extension method to the ServiceExtensions class.

public static void ConfigureIISIntegration(this IServiceCollection services)
        {
            services.Configure<IISOptions>(options =>
            {
                // we do not initialize any of these properties inside,
                // because we are fine with default values 
            });
        }

now it’s time to modify Startup classes ConfigureServices() and Configure() methods to support CORS and IIS integration now with above extension methods.

Startup.cs

using CustomerOrders.Extensions;

namespace CustomerOrders
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method is used to correctly create classes at runtime, 
       // dependencies are registered/ with a container (IServiceCollection) in 
       //  the ConfigureServices method.
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureCors();
            services.ConfigureIISIntegration();
            services.AddControllers(); 
        }
        // This method gets called by the runtime. Use this method to configure 
            the HTTP request pipeline.
        // Configure the middleware pipeline for handling HTTP requests.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();

            // this enables using static files for the request.
            app.UseStaticFiles();
            app.UseCors("CorsPlicy");

           // this will forward proxy headers to the current request.
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.All
            }); ;

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

we have added CORS and IIS configuration to the ConfigureServices method, also CORS configuration has been added to the application’s pipeline in the Configure method.

1.5 Environment-Based Settings:

check my previous post of (https://www.srinadimpalli.com/2019/07/overview-of-asp-net-core-and-setting-up-the-application-configuration/

check section 4, which will explain about environment based settings.

That’s all for now, thank you.

local_offerevent_note August 26, 2020

account_box srinivasaraju nadimpalli


local_offer