Net core web API project and publishing method under nginx

Time:2020-9-11

preface

This article will introduce some basic knowledge of net core and how to release webapi project of net core under nginx.

testing environment

  • Operating system: Windows 10
  • Development tool: Visual Studio 2019
  • Framework: net core 3

Net core webapi project creation

First, create a net core webapi project, corepublishfornginx.

Choose first Asp.Net Core web application, as shown in the following figure:

Then modify the project name, as shown in the following figure:

Then select the API option, as shown in the following figure:

The project is created, as shown in the following figure:

Code introduction

Controller

After the project is created, we can see that an API controller, weatherforecastcontroller, is built in. The code is as follows:


[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
  private static readonly string[] Summaries = new[]
  {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
  };
 
  private readonly ILogger<WeatherForecastController> _logger;
 
  public WeatherForecastController(ILogger<WeatherForecastController> logger)
  {
    _logger = logger;
  }
 
  [HttpGet]
  public IEnumerable<WeatherForecast> Get()
  {
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
      Date = DateTime.Now.AddDays(index),
      TemperatureC = rng.Next(-20, 55),
      Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
  }
}

As shown in the above code, we first see that the controller inherits a class called controllerbase. (webapi inherited in netframework inherits apicontroller, MVC inherits controller)

Then, we find that the controller has a constructor and an input parameter. We know that the call of controller is the internal mechanism of the framework, that is, the framework will give it an input parameter when calling the controller.

From the name, we can find that this is a log input parameter, that is, when the core calls the controller, a logging object is built in for us.

We don’t need to use the log here, so we can delete this constructor first.

Next, we see the body of the API request implementation, get request.

The main embodiment is very simple, that is, the method name is used with get, and then the httpget feature is added to the method header. (the get method name can be modified, because only one get request is supported in a webapi, so as long as the httpget feature is added to the method, it will be regarded as the default get method.)

The get request implements a component of an entity collection, that is, requesting the controller will get an array of entity sets.

Program

After learning controller, we enter Program.cs File, we make a simple modification, set the boot port of kestrel.

Modify the code of createhostbuilder as follows:

public static IHostBuilder CreateHostBuilder(string[] args)
{
  return Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
     webBuilder =>
     {
       //Set the startup file for the project
       webBuilder.UseStartup<Startup>();
       //The default listening ports of kestrel are http5000 and https5001.
       webBuilder.ConfigureKestrel(options =>
       {
         options.ListenAnyIP (5180); // listen to port 5180 of any IP on the local computer, which is equivalent to setting ip0.0.0.0
                      // options.Listen (new IPEndPoint( IPAddress.Parse ("127.0.0.1"), 5180)); // listen to the specified port of the specified IP
       }); ;
     });
}

Startup

Startup is called in the following order:

Startup constructor — configureservices configuration service function — configure request configuration

Startup constructor:

Here we do simple configuration information object extraction. In actual combat, operations like startup log can also be centralized here.

Configureservices configuration service function:

Only one controller service is added here. In actual combat, more services can be added, such as using the services.AddCors Add a cross domain service.

Configure request configuration:

Some request configurations are made here, such as:

app.UseDeveloperExceptionPage () — set the display content of exception request as built-in exception error interface (in MVC mode, you can also specify the display interface when requesting exception, such as: app.UseExceptionHandler (“/Home/Error”);)

app.UseHttpsRedirection () — HTTP request redirection, convert HTTP request into HTTP, and increase some security. (it can also be added app.UseHsts (), requiring the browser to send only HTTPS to achieve double security)

app.UseRouting () — configure endpointroutebuilder.

app.UseEndpoints ——Use the endpoint routebuilder. The combination of userouting and useendpoints realizes routing.

app.UseAuthorization () — authorization processing of the request because no authorization service was added services.AddAuthorization So it’s invalid here.

—————————————————————————————————-

So far, we have a preliminary understanding of the net core web API project. Now we debug it and the project starts and runs normally, as shown in the following figure:

As you can see, the request port 44317 in the figure is not the 5180 that we set. This is because we use fast IIS to start the project during debugging. After publishing, port 5180 will naturally be used.

Dependency injection

Here is a brief introduction to dependency injection provided by NETCORE.

As mentioned above, when the framework calls controller, it provides an input parameter – ilogger object. This behavior is called dependency injection.

The input parameter behavior provided for controller can be customized in NETCORE; now we simply add an object.

First, create a Kiba class and an ikiba interface, as follows:


public interface IKiba
{
  string GetName();
}
public class Kiba: IKiba
{
  public string GetName()
  {
    return "Kiba518";
  }
}

Then inject this object into startup’s configureservices. The code is as follows:

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllers(); 
  services.AddTransient < ikiba, Kiba > (); // dependency injection 
}

Then, in the constructor of controller, add the ikiba type parameter. The code is as follows:


public WeatherForecastController(IKiba _kiba)
{ 
  string name = _kiba.GetName(); 
}

In this way, the dependency injection is completed. We run the code, make breakpoints in the constructor, and test whether we can get the value.

As shown in the figure above, we get the dependency we just injected.

release

Net core web API has been created. Now we will publish the project.

Right click the project and select publish, as shown in the following figure:

After clicking, the interface for selecting publishing target will pop up, as shown in the following figure:

Select the folder in the interface, and then enter the publishing path in the select Folder text box.

Then click advanced to open the advanced configuration interface, as shown in the following figure:

Modify the deployment mode in the configuration to [independent], and the target runtime is [win-x64] (because my tester is x64).

Then click save, the page returns to the previous level, and then click create configuration file.

Then the system enters the release interface, as shown in the following figure:

Click the Publish button to publish, and then wait patiently.

As shown in the figure above, the project has been successfully released. Now enter the release folder and you will see a lot of files, which we can find CorePublishForNginX.exe ; and then double-click run to test whether it can be accessed.

After double clicking, the running results are shown in the following figure:

Webapi project started successfully. Now let’s visit http://127.0.0.1 :5180/weatherforecast。

As shown in the figure above, the access is successful.

PS: it should be noted that the CMD window cannot be closed. Once closed, the website will stop running, because the CMD window is the host process of the website.

Net core web API released under nginx

Now we use nginx’s reverse proxy to send the client’s request to the NETCORE webapi project.

First, go to the official website to download nginx. Click nginx / windows-1.17.8 to download the Windows version of nginx, as shown in the figure below. Official website address: http://nginx.org/en/download.html

After downloading, unzip it to an English directory, as shown in the following figure.

The conf folder is the configuration. Double click to enter the conf folder, as shown in the figure below.

Locate the configuration file in the folder nginx.conf Open it in Notepad and configure it here.

As mentioned above, our webapi project monitors port 5180, while nginx listens on port 80 by default after startup. That is to say, we need to forward the messages monitored by port 80 to port 5180 in the configuration file of nginx.

open nginx.conf File, the modified content is shown in the following figure:

After modification, return to the superior directory and run NginX.exe It should be noted here that nginx does not have a foreground interface, so whether it runs successfully or not should be checked in task management NginX.exe The process of.

Run out NginX.exe , let’s talk about it http://127.0.0.1/weatherforecast To see if the message from port 80 is sent to port 5180.

The running result is shown in the figure above. The message is successfully sent to port 5180.

PS: in nginx.conf In this paper, the annotation symbol is ා. There is a slash “/” after location. The slash represents the root directory. If you want to point to a subdirectory, just add the directory name after the slash, such as / Admin.

—————————————————————————————————-

At this point, we will explain the net core web API project and release under nginx.

The code has been passed to GitHub. You are welcome to download it.

GitHub address: https://github.com/kiba518/CorePublishForNginX

This article about the net core web API project and the method of publishing under nginx will be introduced here. For more related content of net core web API under nginx, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!

Author: kiba518

https://www.cnblogs.com/kiba/p/12286225.html