Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

.NET Core 2.0, Angular 4, and MySQL Part 2 - Project configuration

DZone's Guide to

.NET Core 2.0, Angular 4, and MySQL Part 2 - Project configuration

In this post, we'll learn how to use configuration methods in a Startup class, how to register different services, and how to use extension methods.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

When starting a new project, does basic configuration matter? .NET Core configuration differs greatly from the standard .NET projects. We don't have any more web.config files but, instead, we use the built-in Configuration framework that comes with .NET Core.

Therefore, having a good understanding of how to configure your project and how to configure services, which you will use until the end of the development process, is a must.

In this post, I will explain to you how to use configuration methods in a Startup class. Also, you will learn how to register different services and how to use extension methods to help you achieve this.

If you want to see all the basic instructions and complete navigation for this series, please click on the following link: Introduction page for this tutorial.

For the previous part click on this link: Part 1 - MySQL, creating database data

Creating a New Project and Modifying the launchSettings.json File

After we have finished creating and populating the database, which we did in the previous post, we are going to create a Visual Studio project for our server part of the application. Open Visual Studio 2017 and create a new ASP.NET Core Web Application with the name 'AccountOwnerServer.'

In the next window, choose Web API and from the left drop-down list choose .NET Core. Also, from the right drop-down choose ASP.NET Core 2.0. After all that, just click the OK button and your project will load.

After the project has been created, we are going to modify the launchSettings.json file. Let's change the applicationUrl property and the launchBrowser property to false, to prevent the web browser from starting when the project starts.

In Solution Explorer, expand Properties and double click on the launchSettings.json file. Modify it like this:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": false,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "AccountOwner_Server": {
      "commandName": "Project",
      "launchBrowser": false,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:5000/"
    }
  }
}

Program.cs and Startup.cs Explanations

In Program.cs, you will find this piece of code:

public static void Main(string[] args)
{
     BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

If you are familiar with .NET Core 1.0, you will find that this code is considerably smaller than it used to be. Also, you could think that many parts are missing like UseKestrel() or UseIISIntegration()... but that is not the situation. Method CreateDefaultBuilder(args) encapsulates all that stuff inside, making this code more readable and quite

You will also notice this part of the code: UseStartup<Startup>(). The Startup class is mandatory for .NET Core, in which we configure embedded or custom services that our application needs. When you open the Startup class, you can see the constructor and the two methods whose content we will change during application development. In the method ConfigureServices, you will do exactly that, configure your services. Furthermore, in the method Configure you are going to add different middleware components to application’s request pipeline.

All of our configuration code could be written inside the ConfigureServices method, but large applications could potentially contain many services. As a result, it could make this method unreadable and hard to maintain. Therefore, we will create extension methods for each configuration and place configuration code inside those methods.

Extension Methods and CORS Configuration

An extension method is inherently the static method. What makes it different from other static methods is that it accepts "this" as the first parameter, and "this" represents the data type of the object which uses that extension method. An extension method must be inside a static class. This kind of methods extends the behavior of types in .NET.

So, let's start with writing some code.

Create a new folder called "Extensions" in our project and create a new class inside that folder, with the name ServiceExtensions. We are going to make that class static and inside that class, we will add our service extension methods.

namespace AccountOwnerServer.Extensions
{
    public static class ServiceExtensions
    {
    }
}

First, we need to configure CORS in our application. CORS (Cross-Origin Resource Sharing) is a mechanism that gives rights to the user to access resources from the server on a different domain. Because we will use Angular as the client-side framework on a different domain than server's domain, configuring CORS is mandatory. So add this code to the ServiceExtensions class:

public static void ConfigureCors(this IServiceCollection services)
{
      services.AddCors(options =>
      {
          options.AddPolicy("CorsPolicy",
              builder => builder.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials());
      });
}

We are using the basic settings for adding CORS policy because for this project allowing any origin, method, and header is quite enough. But you can be more restrictive with those settings if you want. Instead of the AllowAnyOrigin() method which allows requests from any source, you could use theWithOrigins("http://www.something.com"), which will allow requests just from the specified source. Also, instead of AllowAnyMethod() that allows all HTTP methods, you can use WithMethods("POST", "GET") that will allow only specified HTTP methods. Furthermore, you can make the same changes for the AllowAnyHeader() method by using, for example, the WithHeaders("accept", "content-type") method to allow only specified headers.

IIS Configuration

Additionally, you need to configure IIS integration which will help us with IIS deployment. Add the following code to the ServiceExtensions class:

public static void ConfigureIISIntegration(this IServiceCollection services)
{
      services.Configure<IISOptions>(options => 
      {

      });          
}

We are not setting up any of the properties inside the options parameter because we are just fine with their default values. For more information about those properties, look at the picture below.

In the Startup class, we will change the ConfigureServices and Configure methods as follows:

public void ConfigureServices(IServiceCollection services)
{
      services.ConfigureCors();

      services.ConfigureIISIntegration();

      services.AddMvc();
}            

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("CorsPolicy");

    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.All
    });

    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == 404
            && !Path.HasExtension(context.Request.Path.Value))
        {
            context.Request.Path = "/index.html";
            await next();
        }
    });

    app.UseStaticFiles();

    app.UseMvc();
}

In the ConfigureServices method, CORS and IIS configuration have been added. Furthermore, CORS configuration has been added to the application's pipeline inside the Configuration method. But as you can see, there is a little more code. Therefore, I will explain it now.

  • app.UseForwardedHeaders will forward proxy headers onto current requests. This will help us during the Linux deployment.
  • app.Use(async (context, next) => ... will point to the index page in the Angular project.
  • app.UseStaticFiles() enables the use of static files for requests. If we don't set a path of static files, it will use a wwwroot folder in our solution explorer by default.

Conclusion

That is all for Part 2 of this tutorial. Now you know how to modify the launchSetting.json file, the purpose of the Program and Startup classes, how to configure services, and, finally, how to create and use extension methods.

Thank you for reading and check out the next part in which we will create our first service, a logger service, and use it for logging our messages.

For any additional questions, please do not hesitate to ask by leaving a comment below.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,.net core ,mysql ,angular ,web application development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}