NetCore环境下的MVC

一, 项目文件的作用

1.Connected Services:这是存放服务引用的, 比如Web Services等。

2.Properties:项目开发的一些基本配置, 比如启动方式, 当前环境等。

3.依赖项:和.Net Framework的引用是一个意思。只不过.Net Core的引用都是基于Nuget管理, 不能直接添加DLL引用。

4.appsettings.json: 该文件是当前项目的配置信息. 等价于.Net Framework的Web.config文件, 可以把项目一些配置信息放在这里, 比如数据库连接字符串等。

5.Program.cs:program.cs中包含Main方法,它是程序的入口点。

6.Startup.cs:主要是用来控制配置服务信息, 注册一些中间件什么的

二,程序启动类 Program.cs 分析

  在 CreateWebHostBuilder 方法中调用了UseStartup方法, 里面用泛型注入了 Startup 类, 那程序就会自动实例化这个类, 并且去执行它里面的 ConfigureServices 和 Configure 这两个方法。

  在ConfigureServices方法里面, 我们可以自定义一些服务。注册完服务, 我们就可以通过依赖注入的方式在其它地方使用这些服务。

  然后再执行的方法就是 Configure 这个方法. 我们能看到 Configure 方法默认的第一个参数是 IApplicationBuilder 接口, 可以理解为整个程序的根, 我们通过这个接口对象, 可以精确的配置获取启用我们的中间件, 使我们的各种中间件组合起来, 形成一个完美的Web应用程序, 去处理我们的HTTP请求并且做出对应的响应等。

三,在Startup.cs的Configure方法里面注入引用自定义的接口

  在Startup.cs的Configure方法里,IConfiguration, IHostingEnvironment, IApplicationBuilder等官方的接口, 我们能直接注入使用, 是因为ASP.Net Core MVC里面的源包里面, 已经自动为我们注册好了这几个服务。我们要使用自定义的服务或者组件, 需要我们自己进行注册。

  Startup.cs里除了Configure方法,还有ConfigureServices方法。它是配置服务用的, 有个IServiceCollection接口参数, 这个接口就是.Net Core默认提供的DI服务的接口管理对象, 我们所有注册的服务都可以通过这个接口进行管理或操作. 如果使用第三方包,那么我们就可以通过IServiceCollection接口进行我们自定义服务的注册了。

  三个注册服务的方法:

  1. AddSingleton (单例模式注册服务, 也就是在整个应用程序中, 只会创建一个接口对象, 所有的请求都会使用这个接口对象, 可能会有并发问题)

    ConfigureServices方法里添加自定义的接口

        public void ConfigureServices(IServiceCollection services)
        {
       //两个泛型参数, 第一个泛型参数是接口, 第二个是泛型参数是接口实现类.   services.AddSingleton<IWelcome, TestWebCoreMVC.Services.Welcome>(); }

  2. AddTransient (管道机制注册服务. 也是在每个请求发生的时候, 都会创建一个接口对象, 给当前请求使用)

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IWelcome, TestWebCoreMVC.Services.Welcome>();
        }

  3. AddScoped (会话机制注册服务. 也就是在当前会话中, 只会创建一个接口对象. 什么是一个会话, 可以简单理解为当前浏览器打开到关闭, 这个过程就是一整个会话的过程)-推荐使用

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IWelcome, TestWebCoreMVC.Services.Welcome>();
        }

例:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.Http;
 8 using Microsoft.Extensions.Configuration;
 9 using Microsoft.Extensions.DependencyInjection;
10 using Microsoft.Extensions.Hosting;
11 using TestWebCoreMVC.Services;
12 
13 namespace TestWebCoreMVC
14 {
15     public class Startup
16     {
17         // This method gets called by the runtime. Use this method to add services to the container.
18         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
19         public void ConfigureServices(IServiceCollection services)
20         {
21             services.AddScoped<IWelcome, TestWebCoreMVC.Services.Welcome>();
22         }
23 
24         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
25         public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, IWelcome welcome)
26         {
27             if (env.IsDevelopment())
28             {
29                 app.UseDeveloperExceptionPage();
30             }
31 
32             app.UseRouting();
33 
34             app.UseEndpoints(endpoints =>
35             {
36                 endpoints.MapGet("/", async context =>
37                 {
38                     //var msg = configuration["WelcomeMsg"];
39                     var msg = welcome.GetWelcomMsg();
40                     await context.Response.WriteAsync(msg);
41                 });
42             });
43         }
44     }
45 }

 四,Startup.cs 分析

  开始,我们在Program.cs的CreateWebHostBuilder 方法中调用了UseStartup方法, 里面用泛型注入了 Startup 类, 那程序就会自动实例化这个类, 并且去执行它里面的 ConfigureServices 和 Configure 这两个方法。

  在Startup.cs的ConfigureServices方法里面,我们可以自定义一些服务。注册完服务,我们就可以通过依赖注入的方式在其它地方使用这些服务。

  然后再执行Configure 这个方法,我们能看到 Configure 方法默认的第一个参数是 IApplicationBuilder 接口, 可以理解为整个程序的根, 我们通过这个接口对象, 可以精确的配置获取启用我们的中间件, 使我们的各种中间件组合起来, 形成一个完美的Web应用程序, 去处理我们的HTTP请求并且做出对应的响应等。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using TestWebCoreMVC.Services;

namespace TestWebCoreMVC
{
    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)
        {
            services.AddScoped<IWelcome, TestWebCoreMVC.Services.Welcome>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, IWelcome welcome)
        {
            if (env.IsDevelopment())        // 开发者环境(异常中间件),输出异常详细信息,如出错代码位置和原代码
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler();  // 正常用户环境,输出404,500等错误页面
            }
            //    env.EnvironmentName = "Cus";    //设置自定义环境名称; 预发布环境-Staging;自定义环境-Cus
            app.UseRouting();               // 根据当前请求找到endpoint;如果去掉 app.UseRouting() 访问时会抛异常

            app.UseEndpoints(endpoints =>   // 拿到上面找到的endpoint去执行请求的最终处理
            {
                endpoints.MapGet("/", async context =>
                    {
                        context.Response.ContentType = "text/plain;charset=utf-8";  //防止WriteAsync方法输出中文乱码
                        if (env.IsDevelopment())
                        {
                            await context.Response.WriteAsync("开发环境", Encoding.UTF8);
                        }
                        else if (env.IsProduction())
                        {
                            await context.Response.WriteAsync("运营环境", Encoding.UTF8);
                        }
                        else if (env.IsStaging())
                        {
                            await context.Response.WriteAsync("预发布环境", Encoding.UTF8);
                        }
                        else
                        {
                            await context.Response.WriteAsync("自定义环境", Encoding.UTF8);
                        }
                        //var msg = configuration["WelcomeMsg"];
                        var msg = welcome.GetWelcomMsg();
                        await context.Response.WriteAsync(msg);
                    });
            });
        }
    }
}
View Code

  IsDevelopment():判断当前是不是开发环境.              - Development

  IsProduction():判断当前是不是运营(正式)环境         - Production
  IsStaging():判断当前是不是预运行环境                     -Staging
  IsEnvironment():根据传入的环境名称, 判断是不是当前环境类型 (用于自定义环境判断)   - Cus

  注:运营环境查看方法:修改一下编译环境, 把Debug修改为Release, 然后生成项目, 生成成功之后, 到项目的bin/Release/netcoreapp2.2目录下, 打开CMD, 执行dotnet Unit1.dll命令。最后在浏览器输入 http://localhost:****/回车。

365个夜晚,我希望做到两天更一篇博客。加油,小白!
原文地址:https://www.cnblogs.com/qq2806933146xiaobai/p/12711894.html