Change the App interface server to dotnet core hosting

Source: Internet
Author: User
Tags httpcontext hosting

Yesterday, one of my app's interface server hung up, foreign chicks accidentally overturned, along with the program and data together, caught off guard. My server program is ASP. NET MVC, chick is the memory of the M-I can't run Windows system, installed mono. The server uses the Jexus, but there is also a apache+php+mysql family bucket that takes up 80 ports, so this interface is reverse proxy through Apache.

In this way, the environment is very complex, I am Ubuntu 16.04 installed mono downloaded nearly a MB of data, after installation is larger, is simply too environmentally friendly, only less than 10G hard drive. So the heart of the server-side program rewrite, other fast food language I will not, it is said Nodejs and Python will soon, deployment is also convenient. But I still use my big C #, fortunately now have dotnet core, but also to everyone Amway, it is a modular development stack, but also the future of all. NET platform, spanning the Windows, Linux, OSX three major systems.

Because my interface is relatively simple, mainly output JSON and a few static pages. So no need to create a Web project, I do not want him to host on the server software to run, to implement the Http listener processing requests, but these dotnet core has been prepared for you a server.kestrel, do not need to build wheels.

About Server.kestrel can refer to this article, more or more official more detailed, portals, as well as source code and examples: Https://github.com/aspnet/KestrelHttpServer

To perform the installation in the Package Management console:

pm>  install-package Microsoft.aspnetcore.server.kestrel-pre

In addition, if you need static file support, the following libraries are required:

pm>  install-package Microsoft.aspnetcore.staticfiles-pre

It is easy to use, instantiate a webhostbuilder in the Main method and call the Run method, and the rest is configured.

var host = new Webhostbuilder ()    . Usekestrel ()    . Useurls ("http://*:5001")    . Usecontentroot (Directory.GetCurrentDirectory ())    . Usestartup<program> ()    . Build (); host. Run ();

Processing requests is simply not easy:

App. Run (Async (context) =>{    byte[] data = Encoding.UTF8.GetBytes ("Hello World");    Await the context. Response.Body.WriteAsync (data, 0, data. Length). Configureawait (FALSE);});

But obviously not strong enough to handle URL routing, then write an abstract class to handle HTTP requests.

Abstract class handlerbase{public    abstract void Process (HttpContext context);}

Here you can save the route with a dictionary<string,handler>:

New dictionary<string, handlerbase>(); _routes. ADD ("/home/hello"new  hello ()); _routes. ADD ("/test/demo"New demo ());

Hello This class needs to inherit the Handlerbase abstract class, overriding the Process method:

Class hello:handlerbase{public    async override void Process (HttpContext context)    {        byte[] data = encoding.u TF8. GetBytes ("Hello World");        Await the context. Response.Body.WriteAsync (data, 0, data. Length). Configureawait (false);}    }

This avoids having to write a heap of if else in order to handle routing, the extensibility is also better, according to the URL path to find the corresponding Handlerbase implementation, and call process processing request.

App. Run (Async(context) ={handlerbase handler=NULL; _routes. TryGetValue (context. Request.Path.ToString (). ToLower (), outhandler); if(Handler! =NULL) handler.    Process (context); Else    {        byte[] data = Encoding.UTF8.GetBytes ("HTTP 404"); awaitContext. Response.Body.WriteAsync (data,0, data. Length). Configureawait (false); }});

Browser Open Effect

Then is the static file processing problem, it is recommended to put a folder to hold static files, such as the creation of the Dotnet Core Web program, there will be a WWW folder.

Kestrel handling static content is also simple:

App. Usestaticfiles (new  staticfileoptions () {    = _fileprovider,    ""     });

Fileprovider is a class that must be implemented with Ifileprovider.

New " www "));

Since Requestpath is an empty string, it is mapped directly to the Abc.txt file under the WWW directory and returned as long as the access/abc.txt.

Publishing a project results in a Publishoutput folder, which copies the contents into the host/home/test directory. To run this project also need to install dotnet core on the server, this does not need to re-compile the original code, how to install can refer to the official website.

Execute the following command to run your project if your project is called demo?? :

Dotnet Demo.dll

Start the program

Finally, if you want to learn more, do not just execute a Hello world, know this matter to preach!

Change the App interface server to dotnet core hosting

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.