课程链接:http://video.jessetalk.cn/course/explore

良心课程,大家一起来学习哈!

任务22:课程介绍

  • 1.HTTP 处理过程
  • 2.WebHost 的配置与启动
  • 3.Middleware 与管道
  • 4.Routing MiddleWare 介绍

任务23:Http请求的处理过程

任务24:WebHost的配置

  • 1.覆盖配置文件
  • 2.更改启动URL
  • 3.IHostingEnvironment
  • 4.IApplicationLifetime
  • 5.dotnet watch run
  1. dotnet new web

settings.json

  1. {
  2. "ConnectionStrings":{
  3. "DefaultConnection":"Server=...;Database=...;"
  4. }
  5. }

Program.cs

  1. public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  2. WebHost.CreateDefaultBuilder(args)
  3. .ConfigureAppConfiguration(configureDelegate=>{
  4. configureDelegate.AddJsonFile("settings.json");
  5. })
  6. .UseStartup<Startup>();

Startup.cs

  1. using Microsoft.Extensions.Configuration;
  2. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration)
  3. {
  4. if (env.IsDevelopment())
  5. {
  6. app.UseDeveloperExceptionPage();
  7. }
  8. app.Run(async (context) =>
  9. {
  10. // await context.Response.WriteAsync("Hello World!");
  11. // JsonFile
  12. await context.Response.WriteAsync(configuration["ConnectionStrings:DefaultConnection"]);
  13. });
  14. }

启动HelloCore,输出结果

Program.cs

  1. public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
  2. WebHost.CreateDefaultBuilder(args)
  3. .ConfigureAppConfiguration(configureDelegate => {
  4. //configureDelegate.AddJsonFile("settings.json");
  5. configureDelegate.AddCommandLine(args);
  6. })
  7. //.UseUrls("http://localhost:5001")
  8. .UseStartup<Startup>();

Startup.cs

  1. app.Run(async (context) =>
  2. {
  3. // await context.Response.WriteAsync("Hello World!");
  4. // JsonFile
  5. //await context.Response.WriteAsync(configuration["ConnectionStrings:DefaultConnection"]);
  6. // CommandLine
  7. await context.Response.WriteAsync($"name={configuration["name"]}");
  8. });

设置应用程序参数

启动HelloCore,输出结果

任务25:IHostEnvironment和 IApplicationLifetime介绍

Startup.cs

  1. app.Run(async (context) =>
  2. {
  3. await context.Response.WriteAsync($"ContentRootPath = {env.ContentRootPath}");
  4. await context.Response.WriteAsync($"EnvironmentName = {env.EnvironmentName}");
  5. await context.Response.WriteAsync($"WebRootPath = {env.WebRootPath}");
  6. });

启动HelloCore,输出结果

Startup.cs

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration, IApplicationLifetime applicationLifetime)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. applicationLifetime.ApplicationStarted.Register(() =>
  8. {
  9. Console.WriteLine("Started");
  10. });
  11. applicationLifetime.ApplicationStopped.Register(() =>
  12. {
  13. Console.WriteLine("Stopped");
  14. });
  15. applicationLifetime.ApplicationStopped.Register(() =>
  16. {
  17. Console.WriteLine("Stopped");
  18. });
  19. app.Run(async (context) =>
  20. {
  21. await context.Response.WriteAsync($"ContentRootPath = {env.ContentRootPath}");
  22. await context.Response.WriteAsync($"EnvironmentName = {env.EnvironmentName}");
  23. await context.Response.WriteAsync($"WebRootPath = {env.WebRootPath}");
  24. });
  25. }

启动HelloCore,输出结果

我心中的ASP.NET Core 新核心对象WebHost(一):

http://www.jessetalk.cn/2017/11/11/aspnet-core-object-webhost/#comment-194

我心中的ASP.NET Core 新核心对象WebHost(二):

http://www.jessetalk.cn/2017/11/14/aspnet-core-object-webhost-build/

任务26:dotnet watch run 和attach到进程调试

New Terminal

  1. dotnet new web --name HelloCore

F5 Start Debug

在csproj 的 ItemGroup 添加引用

  1. <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />

New Terminal

  1. dotnet restore
  2. dotnet watch run

修改代码保存后会自动重启

浏览器刷新即可看到更新结果

attach到进程调试

任务27:Middleware管道介绍

  • 1.Middleware 与管道的概念
  • 2.用 Middleware 来组成管道实践
  • 3.管道的实现机制(RequestDelegate 与 ApplicationBuilder)

startup.cs

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. // 添加一个中间件,传一个名字为next的request delegate
  8. app.Use(async (context,next)=>{
  9. await context.Response.WriteAsync("1: before start...");
  10. await next.Invoke();
  11. });
  12. // 接收一个RequestDelegate,返回一个RequestDelegate
  13. app.Use(next=>{
  14. return (context)=>{
  15. context.Response.WriteAsync("2: in the middle of start..");
  16. return next(context);
  17. };
  18. });
  19. app.Run(async (context) =>
  20. {
  21. await context.Response.WriteAsync("3: start...");
  22. });
  23. }

启动项目,输出结果

  1. // 如果不调用next,则管道终止,不会输出"3: start..."
  2. app.Use(next=>{
  3. return (context)=>{
  4. return context.Response.WriteAsync("2: in the middle of start..");
  5. //return next(context);
  6. };
  7. });

  1. // 使用Map构建路由,通过localhost:5000/task访问
  2. app.Map("/task", taskApp=>{
  3. taskApp.Run(async context=>{
  4. await context.Response.WriteAsync("this is a task");
  5. });
  6. });
  7. // 添加一个中间件,传一个名字为next的request delegate
  8. app.Use(async (context,next)=>{
  9. await context.Response.WriteAsync("1: before start...");
  10. await next.Invoke();
  11. });
  12. // 接收一个RequestDelegate,返回一个RequestDelegate
  13. // 如果不调用next,则管道终止,不会输出"3: start..."
  14. app.Use(next=>{
  15. return (context)=>{
  16. context.Response.WriteAsync("2: in the middle of start..");
  17. return next(context);
  18. };
  19. });
  20. app.Run(async (context) =>
  21. {
  22. await context.Response.WriteAsync("3: start...");
  23. });

访问 https://localhost:5001/task

任务28:RequestDelegate管道实现思路

  • 1.RequestDelegate
  • 2.ApplicationBuilder:多个RequestDelegate拼接
  1. // 添加一个中间件,传一个名字为next的RequestDelegate
  2. app.Use(async (context,next)=>{
  3. await context.Response.WriteAsync("1: before start...");// 完成自己处理
  4. await next.Invoke();// 调用下一步
  5. });
  6. // 封装一个function交给ApplicationBuilder处理
  7. app.Use(next=>{
  8. return (context)=>{
  9. context.Response.WriteAsync("2: in the middle of start..");
  10. return next(context);
  11. };
  12. });

任务29:自己动手构建RequestDelegate管道

新建一个控制台程序

  1. dotnet new console --name MyPipeline

新建一个类RequestDelegate.cs

  1. using System;
  2. using System.Threading.Tasks;
  3. namespace MyPipeline
  4. {
  5. public delegate Task RequestDelegate(Context context);
  6. }

新建一个类Context.cs

  1. using System;
  2. using System.Threading.Tasks;
  3. namespace MyPipeline
  4. {
  5. public class Context
  6. {
  7. }
  8. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. namespace MyPipeline
  5. {
  6. class Program
  7. {
  8. public static List<Func<RequestDelegate,RequestDelegate>>
  9. _list = new List<Func<RequestDelegate, RequestDelegate>>();
  10. static void Main(string[] args)
  11. {
  12. Use(next=>{
  13. return context=>{
  14. Console.WriteLine("1");
  15. return next.Invoke(context);
  16. };
  17. });
  18. Use(next=>{
  19. return context=>{
  20. Console.WriteLine("2");
  21. return next.Invoke(context);
  22. };
  23. });
  24. RequestDelegate end = (Context)=>{
  25. Console.WriteLine("end...");
  26. return Task.CompletedTask;
  27. };
  28. _list.Reverse();
  29. foreach(var middleware in _list)
  30. {
  31. end = middleware.Invoke(end);
  32. }
  33. end.Invoke(new Context());
  34. Console.ReadLine();
  35. }
  36. public static void Use(Func<RequestDelegate,RequestDelegate> middleware)
  37. {
  38. _list.Add(middleware);
  39. }
  40. }
  41. }

在任何一个Middleware可以结束管道

  1. Use(next=>{
  2. return context=>{
  3. Console.WriteLine("1");
  4. //return next.Invoke(context);
  5. return Task.CompletedTask;// 结束管道调用,只输出1
  6. };
  7. });

任务30:RoutingMiddleware介绍以及MVC引入

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Routing;
  5. using Microsoft.Extensions.DependencyInjection;
  6. namespace HelloCore
  7. {
  8. public class Startup
  9. {
  10. // This method gets called by the runtime. Use this method to add services to the container.
  11. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  12. public void ConfigureServices(IServiceCollection services)
  13. {
  14. services.AddRouting();// 添加依赖注入配置
  15. }
  16. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  17. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  18. {
  19. if (env.IsDevelopment())
  20. {
  21. app.UseDeveloperExceptionPage();
  22. }
  23. if (env.IsDevelopment())
  24. {
  25. app.UseDeveloperExceptionPage();
  26. }
  27. // 通过localhost:5000/action访问
  28. app.UseRouter(builder=>builder.MapGet("action", async context=>{
  29. await context.Response.WriteAsync("this is a action");
  30. }));
  31. // 使用Map构建路由,通过localhost:5000/task访问
  32. app.Map("/task", taskApp=>{
  33. taskApp.Run(async context=>{
  34. await context.Response.WriteAsync("this is a task");
  35. });
  36. });
  37. // 添加一个中间件,传一个名字为next的request delegate
  38. app.Use(async (context,next)=>{
  39. await context.Response.WriteAsync("1: before start...");
  40. await next.Invoke();
  41. });
  42. // 如果不调用next,则管道终止,不会输出"3: start..."
  43. app.Use(next=>{
  44. return (context)=>{
  45. return context.Response.WriteAsync("2: in the middle of start..");
  46. //return next(context);
  47. };
  48. });
  49. app.Run(async (context) =>
  50. {
  51. await context.Response.WriteAsync("3: start...");
  52. });
  53. }
  54. }
  55. }

访问 https://localhost:5001/action

使用UseRouter方法2

  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Routing;
  5. using Microsoft.Extensions.DependencyInjection;
  6. namespace HelloCore
  7. {
  8. public class Startup
  9. {
  10. // This method gets called by the runtime. Use this method to add services to the container.
  11. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  12. public void ConfigureServices(IServiceCollection services)
  13. {
  14. services.AddRouting();// 添加依赖注入配置
  15. }
  16. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  17. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  18. {
  19. if (env.IsDevelopment())
  20. {
  21. app.UseDeveloperExceptionPage();
  22. }
  23. if (env.IsDevelopment())
  24. {
  25. app.UseDeveloperExceptionPage();
  26. }
  27. // 使用UseRouter方法2
  28. // 通过localhost:5000/action访问
  29. RequestDelegate handler = context=>context.Response.WriteAsync("this is a action");
  30. var route = new Route(
  31. new RouteHandler(handler),
  32. "action",
  33. app.ApplicationServices.GetRequiredService<IInlineConstraintResolver>()
  34. );
  35. app.UseRouter(route);
  36. // 使用UseRouter方法1
  37. // 通过localhost:5000/action访问
  38. app.UseRouter(builder=>builder.MapGet("action", async context=>{
  39. await context.Response.WriteAsync("this is a action");
  40. }));
  41. // 使用Map构建路由,通过localhost:5000/task访问
  42. app.Map("/task", taskApp=>{
  43. taskApp.Run(async context=>{
  44. await context.Response.WriteAsync("this is a task");
  45. });
  46. });
  47. // 添加一个中间件,传一个名字为next的request delegate
  48. app.Use(async (context,next)=>{
  49. await context.Response.WriteAsync("1: before start...");
  50. await next.Invoke();
  51. });
  52. // 如果不调用next,则管道终止,不会输出"3: start..."
  53. app.Use(next=>{
  54. return (context)=>{
  55. return context.Response.WriteAsync("2: in the middle of start..");
  56. //return next(context);
  57. };
  58. });
  59. app.Run(async (context) =>
  60. {
  61. await context.Response.WriteAsync("3: start...");
  62. });
  63. }
  64. }
  65. }

访问 https://localhost:5001/action

RountingMiddleware介绍

  1. var routeHandler = new RouteHandler(context=>context.Response.WriteAsync("test"));
  2. var route = new Route(routeHandler);
  3. new RouteMiddleware(route)
  4. RouteMiddleware.Invoke(httpContext)
  5. _route.RouteAsync(context)
  6. routeMatch(RouteContext)
  7. OnRouteMatched(RouteContext)

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。

ASP.NET Core快速入门(第4章:ASP.NET Core HTTP介绍)--学习笔记的更多相关文章

  1. ASP.NET Core 快速入门(Razor Pages + Entity Framework Core)

    引子 自从 2009 年开始在博客园写文章,这是目前我写的最长的一篇文章了. 前前后后,我总共花了 5 天的时间,每天超过 3 小时不间断写作和代码调试.总共有 8 篇文章,每篇 5~6 个小结,总截 ...

  2. ASP.NET Core快速入门--学习笔记系列文章索引目录

    课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 抓住国庆假期的尾巴完成了此系列课程的学习笔记输出! ASP.NET Core快 ...

  3. 【笔记目录2】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总

    当前标签: ASP.NET Core快速入门 共2页: 上一页 1 2  任务27:Middleware管道介绍 GASA 2019-02-12 20:07 阅读:15 评论:0 任务26:dotne ...

  4. 【笔记目录1】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总

    当前标签: ASP.NET Core快速入门 共2页: 1 2 下一页  任务50:Identity MVC:DbContextSeed初始化 GASA 2019-03-02 14:09 阅读:16 ...

  5. 【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  6. 【第一篇】ASP.NET MVC快速入门之数据库操作(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  7. .NET Core 快速入门教程

    .NET Core 快速学习.入门系列教程.这个入门系列教程主要跟大家聊聊.NET Core的前世今生,以及Windows.Linux(CentOS.Ubuntu)基础开发环境的搭建.第一个.NET ...

  8. .NET Core快速入门教程 2、我的第一个.NET Core App(Windows篇)

    一.前言 本篇开发环境?1.操作系统: Windows 10 X642.SDK: .NET Core 2.0 Preview 二.安装 .NET Core SDK 1.下载 .NET Core下载地址 ...

  9. .NET Core快速入门教程 3、我的第一个.NET Core App (CentOS篇)

    一.前言 本篇开发环境?1.操作系统:CentOS7(因为ken比较偏爱CentOS7)2.SDK版本:.NET Core 2.0 Preview 你可能需要的前置知识1.了解如何通过Hyper-V安 ...

  10. 【第二篇】ASP.NET MVC快速入门之数据注解(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

随机推荐

  1. Java自定义注解(1)

    Java注解简介 1. Java注解(Annotation) Java注解是附加在代码中的一些元信息,用于一些工具在编译. 运行时进行解析和使用,起到说明.配置的功能. 注解相关类都包含在java.l ...

  2. Python爬取猪肉价格网并获取Json数据

    场景 猪肉价格网站: http://zhujia.zhuwang.cc/ 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获 ...

  3. Javase之多线程(2)

    多线程(2) 线程的生命周期 新建:创建线程对象 就绪:有执行资格,没有执行权 运行:有资格运行,有执行权 ​ 阻塞:由一些操作让线程处于改状态.没有执行资格,没有执行权,而通过另一些操作激活它,激活 ...

  4. Dynamics 365 登录报错:MSIS7042

    微软动态CRM专家罗勇 ,回复329或者20190504可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 今天访问我的CRM环境报错,AD FS登录页面输入用户名和密码登 ...

  5. LayoutSubviews的调用

    1.当view被添加到另一个view上时调用 2.布局子控件时调用 3.屏幕旋转的时候调用 4.当view的尺寸大小改变的时候调用

  6. 剑指offer 17:合并两个有序链表

    题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则.   解题思路 链表基础操作考察,难点在于对于输入数据的把握,一定要考虑输入数据的全面性 1.出现 ...

  7. 6.python3实用编程技巧进阶(一)

    1.1.如何在列表中根据条件筛选数据 # 1.1.如何在列表中根据条件筛选数据 data = [-1, 2, 3, -4, 5] #筛选出data列表中大于等于零的数据 #第一种方法,不推荐 res1 ...

  8. 接口是用get还是post,如何选择?

    为了保证信息安全性,注册.登录等操作通常都会使用POST请求,GET请求一般用来获取信息 GET与POST的区别可以参考下方链接 https://www.cnblogs.com/hyddd/archi ...

  9. python3.5.3rc1学习四:类

    class calculator: def add(x,y): return x + y print(added) def sub(x,y): return x - y print(sub) def ...

  10. MongoDB Shell基本操作(五)

    官网文档:https://docs.mongodb.com/ 1. 创建数据库 #如果数据库不存在,则创建数据库,否则切换到指定数据库 use DATABASE_NAME 示例: use runoob ...