Write asp.net core 2.0 Web API infrastructure from scratch (1)

Source: Internet
Author: User
Tags blank page webhost


Tools:



1.Visual Studio 2017 v15.3.5+



2.Postman (app for Chrome)



3.Chrome (preferably)



The relevant knowledge about. NET core or. NET Core 2.0 is not covered, primarily from the basic framework for writing a asp.net core 2.0 Web API from scratch.






I've been using the ASP.net Web API (the traditional. NET Framework) as a background API for the last few years, and the front desk uses ANGULARJS 1.2 or 1.6 for development and has done more than 10 projects based on these two technologies. Before that, I was doing Java, because I was not limited to the company, so I decided to give up Java,. NET is very suitable for me.



I've been focusing on asp.net core and angular 2/4, and I've been using this to develop some relatively small projects. Now I feel it's time to use these two technologies to develop bigger projects for the enterprise, since the enterprise sometimes requires SSO (single sign-on), I have been waiting for the official version of the identity Server4 and related libraries, now that the RC version of 2.0 is available, so this is ready to start writing.



This series is where I started my own background API infrastructure based on the ASP.net core 2.0 Web API, and it's estimated to score several times to finish. If there is anything wrong, please point out!!, thank you.



To Create a project:



1. Select ASP.net core Web application.






2. Select. NET core, ASP.net core 2.0, and then select empty (because it is starting from scratch):






Here's a look at the code generated by the project: Program.cs





Namespace Corebackend.api
{public class program
 {public static void Main (string[] args)
 {
 buildwebhost (args).       Run ();
 public static Iwebhost Buildwebhost (string[] args) =>
 webhost.createdefaultbuilder (args)
 . Usestartup<startup> ()
 .   Build ();
 }
}


This program is the entrance to the procedure and looks familiar because the ASP.net core application is actually the console program (console application).



It is a console application that invokes the ASP.net core-related library.



the contents of the main method are mainly used to configure and run the program.



Because our web program requires a host, Buildwebhost This method creates a Webhostbuilder. And we also need a Web Server.



Look at the source code of Webhost.createdefaultbuilder (args) :


public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {            var builder = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureAppConfiguration((hostingContext, config) =>
                {                    var env = hostingContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);                    if (env.IsDevelopment())
                    {                        var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));                        if (appAssembly != null)
                        {
                            config.AddUserSecrets(appAssembly, optional: true);
                        }
                    }

                    config.AddEnvironmentVariables();                    if (args != null)
                    {
                        config.AddCommandLine(args);
                    }
                })
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddConsole();
                    logging.AddDebug();
                })
                .UseIISIntegration()
                .UseDefaultServiceProvider((context, options) =>
                {
                    options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
                });      
       return builder;
        }


asp.net core has two kinds of HTTP servers, one is weblistener, it can only be used for Windows system, the other is Kestrel, it is cross-platform.



Kestrel is the default Web server, which is enabled by means of the Usekestrel () method.



But when we developed the use of IIS Express, the way to invoke useiisintegration () is to enable IIS Express, which acts as a Kestrel Reverse Proxy Server To use.



If deployed on a Windows server, you should use IIS as a Kestrel reverse proxy server to manage and broker requests.



If you are on Linux, you can use Apache, Nginx, and so on as the proxy server for Kestrel.



Of course, you can use Kestrel alone as a Web server, but using IIS as a reverse proxy is a lot of things: for example, IIS can filter requests, manage certificates, and automatically restart programs when they crash.



usestartup<startup> (), which means that when the program starts, we call the Startup class.



After build () Returns an instance (Webhostbuilder) that implements the Iwebhost interface, and then calls Run () runs the Web program and blocks the calling thread until the program shuts down.



Buildwebhost This lambda expression is best not to be integrated into the main method, because the Entity Framework 2.0 uses it, and if you remove the lambda expression, Add-migration This order may not be used!!! Startup.cs





namespace CoreBackend.Api
{    public class Startup
    {        // This method gets called by the runtime. Use this method to add services to the container.        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}





In fact, startup is a real entry point for the program.



The configureservices method is used to add Services (register) to container, such as identity, EF, MVC, etc. including third parties, or written by themselves. (ASP.net core container) and configure these services. This container is used for dependency Injection (Dependency injection). All injected services (in addition to some of the frameworks already registered services) can be injected into (inject) when writing code later. For example, the parameters of the above configure method, app, env, loggerfactory are all injected services.



The Configure approach is to asp.net the core program to specify how each HTTP request is handled , for example, if we can let the program know that I use MVC to process HTTP requests, then invoke the app. USEMVC () This method is OK. But for now, all HTTP requests will result in the return of "Hello world!."



Order of invocation of these methods : Main-> configureservices-> Configure request pipeline and Middleware (request Pipeline, middleware)



Request Pipeline : The code that handles HTTP requests and returns responses constitutes the request pipeline(requesting pipeline).



Middleware : All we can do is use some programs to configure those request pipeline to handle requests and responses. such as processing validation (authentication) procedures, even MVC itself is a middleware (middleware).






Each layer of middleware can directly return or call the next middleware upon request. A better example would be to invoke the authentication validation middleware at the first level, and if the validation fails, return directly to a response that represents an unauthorized request.



app. Usedeveloperexceptionpage (); It's a middleware, and when exception happens, the program handles it. The Judgment env.isdevelopment () indicates that this middleware will only be invoked in the development environment .



You can see this setting on the project's Properties Debug page:






Note that this environment variable development has nothing to do with the debug build inside vs .



In a formal environment, when we encounter Exception, we need to capture and record it (log), we should use this middleware:exception Handler middleware, we can call it this way:


 if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }            else
            {                app.UseExceptionHandler();
            }


Useexceptionhandler can pass parameters, but for the time being, we are in app. The Run method throws an exception and then runs the program, and when you press F12 in Chrome you will find a 500 error (or several, how many requests, how many errors). middleware used to create the Web API:



The original. NET uses the ASP.net Web API and asp.net MVC to create Web APIs and MVC projects, respectively. But ASP.net core MVC integrates them together. MVC Pattern



Model-view-controller It is defined as: MVC is an architectural design pattern for implementing the UI. But there are a lot of explanations on the Internet, and sometimes it's a little confusing. But it certainly has a few of these: loose coupling, SOC (separation of concerns), easy to test, strong reusability, etc.



However, MVC is definitely not a complete program architecture, in a typical n-tier architecture (presentation layer presentation layer, business Layer business layer, data access layer, and service), and MVC is usually a presentation layer. For example, angular is a client-side MVC pattern.



View in the Web API is a display of data or resources, usually JSON. register and use MVC



Because ASP.net Core 2.0 uses a all-inclusive metapackage, these basic services and middleware do not need to be installed separately.



First, register MVC with container in configureservices: services. Addmvc ();


Public void ConfigureServices(IServiceCollection services)
         { services.AddMvc(); // Register MVC to Container
         } 


And then configure inside tells the program to use MVC middleware:





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





Note the order, which should invoke the app after the middleware that handles the exception . USEMVC (), so the middleware that handles the exception can handle the exception between handing the request to MVC and, more generally, it can also capture and process the exception in the execution of the code that returns the MVC correlation.



Then don't forget to put the app. Run that part of the code removed. Then change back to Develpment environment, run, try the effect:



Chrome displays a blank page, pressing F12 to show the 404 Not Found error.



This is because I only added the MVC middleware, but it did nothing and found no code that could be used to process the request, so we added controller to return the data/resources, and so on. asp.net Core 2 metapackage and Runtime Store



asp.net Core 2 metapackage, asp.net core 2.0, all the necessary and common libraries also include a few third-party libraries that have been rounded up and into this all-inclusive asp.net Core 2 metapackage, so open The sender does not have to own a library installation and there is no version matching problem.



Runtime Store, a bit like the previous GAC, has a folder inside the system that contains all the libraries ASP.net Core 2 programs need to run (My computer is: C:\Program files\dotnet\store\x64\ netcoreapp2.0), each asp.net Core 2 application that runs on this computer simply calls these libraries.



Its advantages are:



Fast deployment, no need to deploy the library where the bread contains;



Saves hard disk space, and multiple applications use the same store, without having to deploy these library files within each program's folder.



The program starts faster. Because these libraries are precompiled.



The disadvantage is that the. NET core 2.0 needs to be installed on the server


Related Article

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.