ASP. Net core web API tutorial project configuration

Time:2022-6-25

preface:

This series of articles mainly refer to the Book Ultimate asp.net core 3 web API, translate the original text, and appropriately delete and modify some contents.

For some concepts and principles, the original book and this article have not been described in detail. If they are introduced in detail one by one, the content will be cumbersome and confusing. Personally, I read the original book first to understand the main content, and then specifically search for the concepts and knowledge points that I do not understand or are interested in.

As my technical level and English level are limited, and it is mainly for the convenience of my own review in the future, I have some mistakes. Please criticize and correct me.

Project configuration

Introduction to this chapter: Configuration It is crucial in the development process that we first need to understand how to configure our application. Before Net framework project, we usually use web Config file to complete the configuration of the application Net core, we no longer use this file, but useNET Core Built inConfiguration Frame. This article will introduceStartup Class and how to set up the application through these methods. In addition, it will also introduce how to register the service and how to implement the registration through the extension method.

1. create a new project

Open visual studio 2019, click create a new project, and then select asp NET Core Web API :

Fill in the project name and select the project path:

Then select the target framework and click Create:

2. launchSettings. JSON file

After the project is successfully created, theProperties Can be seen under the node launchSettings.json File:

This document determinesASP.NET Core As you can see, the application startup behavior includes IIS and self managed applications( self-hosted Kestrel Configuration of the startup settings for.


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


Since we are developing a web API project, we do not need to use a browser to view the API like a web project. We will call and view the output of the API through postman (described later). In order to prevent the browser from opening automatically when the application starts, you need tolaunchBrowser Property value set tofalse

"launchBrowser": false

When creating a project, if checkedConfigure for HTTPS In theapplicationUrl There will be two URLs in the node, one for HTTP and the other for HTTPS.

be careful:This HTTPS configuration item is as effective as possible in the local environment. After the application is formally deployed, a real and valid certificate must be configured.

When developing applications locally, there is another important attribute:launchUrl , which defines the default URL to navigate to when the application starts. For this attribute to take effect, you need to set thelaunchBrowser Property value is set to true.

3. Program. CS and startup cs

ASP. Net core application is essentially a console application. It creates a web server to host applications, listen to incoming HTTP requests, and then return responses. Therefore, the entry of the program is still the main () method of the program class, asp The programs in the net core web API application are as follows:


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>();
            });
}

For the host startup process, please refer to: Supplement later.

CreateDefaultBuilder(args)Method to set the default configuration file and variables for the project, as well as the log provider. Configuring the log provider early in the application startup process means that you can use logging to record problems that occur during startup.

After that, call webBuilder.UseStartup<Startup>() Method to initializeStartup Class,Startup Class in ASP.NET Core Web API The project is a mandatory class. You need to configure embedded or customized services required by the application in this class. The code is as follows:


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

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

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

Where, as indicated by the method name, ConfigureServices() Method is used to configure services used by applications, and services are reusable code that adds functionality to applications. stayConfigure() Method will add different middleware to the request pipeline of the application.

Since larger applications may contain many different services, the ConfigureServices() There may be a lot of code in the method, which will make the code look cluttered and poor readability. In order to improve the readability of the code, we can separate the code that adds the service into extension methods one by one.

4. extension method and CORS configuration

The extension method is essentially a static method. It differs from other static methods in that it accepts this as the first parameter, which represents the data type of the object using the extension method.

Extension methods must be defined in static classes, which extend the Net. Once an extension method is defined, it can be chained multiple times on an object of the same type.

Next, start writing code. First, create a new folder in the project:Extensions

Then create a class in this folder: ServiceExtensions , and change this class to a static class. The code is as follows:


public static class ServiceExtensions
{

}

Next, we will start to implement a specific function, so that we can see how to use static classes. The first thing we need to do is to configure CORS in the application.CORS ( Cross-Origin Resource Sharing, cross resource sharing) is a mechanism to grant or restrict access to applications from different domains.

If we want to send requests to applications from different domains, we must configure CORS. So the next step isServiceExtensions Class to allow all requests from all domains to be sent to our API:


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

We use the basic CORS policy settings for the time being, because all sources are allowed at present(origin ), all types of methods and all headers are acceptable. However, if it is a production environment, we should set the policy as strictly as possible.

When necessary, we can use withorigins(“ https://example.com “) method to restrict requests to only one specific source, instead of using allowanyorigin() method to allow requests from all sources. Similarly, you can use WithMethods("POST","GET") Method to restrict the request to a specific HTTP method instead of using theAllowAnyMethods() Method allows all types of HTTP methods. In addition, you can use WithHeaders("accept","content-type")Method to restrict requests to contain specificheaders

5. IIS configuration

ASP.NET CoreApplication is self managed by default(self hosted)Of course, we can also configure IIS integration to help us use IIS hosting for our applications. We can add the following extension methods:


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

    });

At present, we can use the default configuration, so we do not initialize any properties of options in the above code. If you want to modify some configurations, you can refer to the official documentation:

So far, we have written an extension method to support CORS and IIS integration. Next, we willStartup Class, pay attention to the reference namespaceusing CompanyEmployees.Extensions , ConfigureService() The codes are as follows:


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //custom extension methods
    services.ConfigureCors();
    services.ConfigureIISIntegration();
    
    services.AddControllers();
}

For directConfigureServices() Method can make the code more concise and readable after using the extension method. In addition, the naming of extension methods should be as accurate and clear as possible.

We have successfully added CORS and IIS configurations to the service container of the application, but we have not really used these services, so we need toConfigure() Method to add some code that uses the service:


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    //custom pipeline start
    app.UseStaticFiles();

    app.UseCors("CorsPolicy");

    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.All
    });
    //custom pipeline end

    app.UseRouting();

    app.UseAuthorization();

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

Of which,

  • UseForwardedHeaders() : to be forwardedheader The matching field applied to the current request. By convention, the HTTP proxy forwards messages from the client using the well-known HTTP header. The middleware reads theseheader And fillHttpContext Related fields on.
  • UseStaticFiles() Enable the static file service for the currently requested path, which means that the files in the current directory can be accessed through the path. If the path of the static file directory is not set, the wwwroot directory is used by default.
  • UseCors() : add CORS middleware to the request pipeline of the application to allow cross domain requests.

6. other codes in startup class

ConfigureServices() Method,

AddControllers(): add the controller’s service to the service collection.AddMvc() Method can also add a controller to the service collection, but it adds views and pages to the service collection in addition to the controller. Our project is a web API project, so we only need a controller.

Configure() method:

  • UseRouting() : add the routing middleware to the request pipeline.
  • UseAuthorization() : add the authorization middleware to the request pipeline.
  • UseEndpoints() : add an endpoint for the controller’s action and add the endpoint to the route.

7. environment based settings

When developing applications, we use development(development)Environment. After we release the application, we need to use production(production)Environment. The development environment and production environment correspond to different URLs, ports, connection strings, passwords and other sensitive information. So we need to distinguish the configuration according to the environment Net core is easy to implement.

When we create a project, we can see it in the root directory of the project appsettings.json File, which is our main configuration file. Click the arrow in front of the file to see a appsettings.Development.json Documents. If you open the project directory in the file explorer of the system, you can see that these are two different files, but in the Visual Studio In, the two profiles are associated.

appsettings.{EnvironmentSuffix}.json Is a configuration file for a specific environment, which can be overwritten appsettings.json Configuration in the file. asFruit appsettings {EnvironmentSuffix}. jsonThere are and in the fileappsettings.json A key value pair with the same name as the file will overwrite the value of the key value pair. In addition, we can customize a specific environment. For example, for the production environment, we can add another file: appsettings.Production.json :

appsettings.Production.jsonThe file should contain configuration items for the production environment.

In order to set the application runtime environment, we need to set ASPNETCORE_ENVIRONMENT Environment variables. For example, if you want an application to run in a production environment, you need to change the value of the above environment variable toProduction 。 In the windows environment, you can enter the command: SetASPNETCORE_ENVIRONMENT=Production To achieve. In the Linux environment, you can enter the command: exportASPNET_CORE_ENVIRONMENT=Production To achieve.

ASP. Net core application determines which Appsettings to use through the values of the above environment variables JSON files, for example, in a production environment, will useappsettings.Production.json Documents. DefaultLower aspnetcore_ ENVIRONMENTThe value of the variable isDevelopment , openlaunchSettings.jsonFile can see:

For application development, logging is a very important function. Whether in development or after deployment, logging helps us find and record problems. We can locate, reproduce and repair problems according to logs. Therefore, it is necessary to add logging services to applications as early as possible,

This is about asp Net core web API tutorial project configuration article is introduced here, and more related asp Net core web API tutorial content please search the previous articles of developeppaer or continue to browse the related articles below. I hope you will support developeppaer in the future!