"ASP. NET Core" installs Nginx in Linux subsystem and configures reverse proxy

Source: Internet
Author: User
Tags dotnet nginx server nginx reverse proxy

In a bird text, the old week has been introduced in the Ubuntu subsystem installation of Dotnet-sdk method, the old week to the big partners to talk about installing Nginx services, and configure the reverse proxy. Similarly, the old week assumes that you have never used Linux, so the old week will be very thin. Perhaps because of this, the blog park every time the old week's article ere page. Regardless of him, he withdrew him, I pushed me, who was afraid of WHO.

In fact, you can choose Nginx or Apache, but the old week more like nginx some, always feel Apache somewhat awkward. Of course, an ASP. NET core application can run independently, so you can actually expose the URL directly to the application without using a reverse proxy. However, the official recommendation is to use the server component to reverse proxy.

The so-called reverse proxy, plainly, is this: The client sends an HTTP request, first received by the Nginx Service request, and then forwarded the HTTP request to the ASP. NET Core application, after the request processing, the response message is returned along the original path, from the. The NX service sends back to the client.

OK, say less P, let's get started.

Installing Nginx Service

In the previous article, the old week said to change the package update source (sources.list) to a domestic source, because foreign sources are sometimes slow, and often hang out. Last week, the demo is the use of NetEase's open source image, the speed is very fast. Now, let's execute this command, it's a good habit to update the software source every time you install the software.

sudo apt update

This command only updates the source of the software, which is the source you configured in Sources.list or SOURCES.LIST.D, is not really updating the software, to perform package updates, you can execute:

sudo apt upgrade

Now, let's install Nginx.

sudo apt install nginx

To run Nginx, enter the following command.

sudo nginx

Then, access the http://localhost in the browser, if you see the following, it means that your nginx is no problem.

Please pay serious attention , nginx default is 80 port, please ensure that there is no other 80 port service running, including IIS, if it is a Linux subsystem, it is the resources of the common Windows.

Configuring the Reverse Proxy

We want to configure the file in the/etc/nginx/sites-enabled directory, there is a default file, we just need to modify it.

To avoid permissions problems, you can switch to the root context first.

Su

Then enter the root password you set.

Navigate to the/etc/nginx/sites-enabled directory.

Cd/etc/nginx/sites-enabled

Then you can do LS, and you'll see a file called default.

If you do not trust, you can use the CP default Def.bak backup, here I do not back up, directly X out of all its contents.

"' default

The above command was introduced earlier in the week, so that the contents of the file can be emptied and then edited with the Nano tool.

Default

Enter the following in the text:

server{       ;        /{                   proxy_pass http://localhost:15000;                    proxy_set_header Host $host;                    1.1 ;                 }}

Nginx can be configured according to different modules, here we need to configure the reverse proxy, that is, the Ngx_http_proxy_module module, the module of the field you do not have to remember, in the Nginx official website can be found in the full document.

Old week first to tell you the Nginx configuration of the file model bar. It's actually formatted like a C-style class:

< block name >{      field name 1 field value 1;      Field Name 2 field value 2;      Field Name 3 field value 3;      ... Field name F               {                     field name 1 field value 1;                     Field Name 2 field value 2;                     ...               }

First you need to put a server node.

server{...         }

The Listen field represents the listening port, this is 80, generally do not have to change.

Then we need a configuration of the path, that is, location, the reverse proxy is for forwarding, so this path we use/, to represent the root directory.

Location/{            ...}

Then you configure several fields for the location node, all starting with a proxy.

Proxy_pass: This is to fill in our ASP. NET Core Application listening port, the default is 5000, host name you directly write localhost can, because the Nginx reverse proxy, dotnet application is not public, so you do not have to fill the site domain name, The request sent by the client is first to Nginx and then forwarded to the Dotnet application. Therefore, you only need to let the Nginx server public on the line.

Proxy_set_header: This field is configured to add HTTP headers when Nginx receives a client request and forwards the message to an ASP. NET core application, which you can set according to the actual situation, if you feel that there is no header useful, you can not configure. Here I pass the host header, the value is the variable $host, this is a local variable, the runtime will be populated by the Nginx service specific host name.

Proxy_http_version: This is the version number, and you can ignore it.

In the final analysis, the key to the entire configuration is the Proxy_pass field, which only assigns values to the Nginx service to know where your ASP. NET Core application listens for smooth forwarding.

When you're done, press CTRL + O to save, and then press CTRL + X to exit.

Then execute the-t parameter to verify that the above configuration is correct.

Nginx-t

If you see the "test is successful" description is configured correctly.

Then you have to let Nginx reload the configuration so that it will take effect.

Nginx-s Reload

Test effect

Let's create a new ASP. NET Core Application project to test, type choose "Empty" on the line, old week like empty template, flexible.

Modify the Main method so that the listening port points to the 15000 port number specified in the Nginx configuration just above.

 public  static  void  Main (string  [] args) {Bu Ildwebhost (args).        Run ();  public  static  iwebhost Buildweb Host (string  [] args) => Webhost.createdefa Ultbuilder (args). Usestartup  <startup> ()  . Useurls (      "  http://localhost:15000       )  . Build ();  

You can use the Useurls method to specify the URL of the listener, of course, you can also use the configuration file (. json) to set, or you can specify a wildcard domain name http://*:15000.

Then modify the Startup class. In the Configureservices method, add the MVC service feature.

         Public void configureservices (iservicecollection services)        {            services. Addmvc ();        }

Enable the MVC feature in the Configure method.

         Public void Configure (Iapplicationbuilder app, ihostingenvironment env)        {            if  (env. Isdevelopment ())            {                app. Usedeveloperexceptionpage ();            }           app. Usemvc ();        }

Note that these two places are different, the front addmvc just add this feature, and it is not enabled, so you then have to enable the feature through the use method and insert the MVC-related middleware into the HTTP communication pipeline to handle the HTTP request.

Our project is only used to test the character, so the old week will not abide by the norms of MVC, do not build views, controllers and other catalogs, anyway, the old week has always been not in accordance with the regular card. Directly in the project to create a new class, the name you casually take, according to the Convention, should be called Xxxcontroller, of course, you can not call, called Cat, called Pig, as long as the class is inherited from the Controller class, the runtime can also be recognized.

     Public classDemocontroller:controller {[HttpGet ("/")]         PublicIactionresult Start () {returnView ("~/main.cshtml"); } [HttpPost ("/setdata")]         PublicIactionresult Setdata ([Fromform]intA, [Fromform]intb) {intr = A +b; returnView ("~/show.cshtml", R); }    }

Note that the class must be public, and the members of the class should be public, otherwise it won't work. The first action method called Start, I add the HttpGet feature, get access, and specify the "/" template, indicating that you can execute the start method from the root URL of the application, that is, input http://localhost:15000/, you can access. The second action method, called Setdata,httppost, is accessed by POST, and the path is http://localhost:15000/setdata.

The Setdata method has two parameters, A and B. I gave them fromform. What do you mean, that is, the <form> element POST on the client page must contain two fields called A and B, so that the parameters A and B will automatically get the value. For example, the client POST is a=5&b=9, then the parameters of the Setdata method can get the value a = 5,b = 9.

Since this example does not establish the Views folder, the default search rule is not to find the view, so it is important to specify the full file name of the view. Before you create a new view page, you build a layout page that you can use as a motherboard. The file name is _layout.cshtml and the contents are as follows:

<!DOCTYPE HTML><HTML><Head>    <Metaname= "Viewport"content= "Width=device-width"CharSet= "Utf-8" />    <title>@ViewBag. Title</title></Head><Body>    <Div>@RenderBody ()</Div></Body></HTML>

The Renderbody method specifies that when the other view page is applied to the master page, it replaces the renderbody with its contents.

Now let's create a new view page--main.cshtml.

@{Layout = "~/_layout.cshtml";}<Div>    <Div>        <H3>Please enter a parameter</H3>    </Div>    <Div>        <formMethod= "POST"Action= "/setdata">            <Div>                <label for= "a">First Number:</label>                <inputtype= "text"name= "a"/>            </Div>            <Div>                <label for= "B">Second Number:</label>                <inputtype= "text"name= "B"/>            </Div>            <Div>                <Buttontype= "Submit">Are you sure</Button>            </Div>        </form>    </Div></Div>

The Layout property references a master page. The action value of the form element points to the Setdata method, which we have just defined with the HttpPost attribute whose path is/setdata.

The following is the second view page--show.cshtml.

 @{Layout = "~/_layout.cshtml";}   @model int   <  div     >  <  div  >  calculation result: </ div  >   <   Div  >  @Model </ div  >   </ div  >  

Use the @model directive to specify the type of the model property that is the current view, where int is used, and why, do you remember the Setdata method?

         Public Iactionresult Setdata ([fromform]int A, [fromform]int  b)        {            int r = A + b ;              return View ("~/show.cshtml", R);        }

The last sentence, while returning the View page, also passes the value of the variable R, which is the int type, so the Model property should be defined in the show.cshtml page with the int type.

On the page, the Model property is accessed to get the calculated results.

< Div >@Model</div>

OK, this example is finished, run the example first, then make sure Nginx is running in the Linux subsystem, and if you're not sure, you can enter

Service Nginx Status

If you see this, it means that Nginx is running.

If not running, the simplest way, directly input Nginx enter, will run.

Enter http://localhost in the browser, return, the default port is 80, do not lose the port number.

If this is the case, check that the ASP. NET Core app is running.

We randomly enter two integers.

Then commit, you will see the result of adding two integers.

This indicates that the NGINX has successfully forwarded the HTTP message, and the reverse proxy is successfully completed.

Well, dinner time, today is boiled beef, a long time without eating beef, hurriedly dinner.

Please click here for the sample source code in this article.

"ASP. NET Core" installs Nginx in Linux subsystem and configures reverse proxy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.