ASP.NET Core快速入门(第4章:ASP.NET Core HTTP介绍)--学习笔记
点击蓝字关注我们
课程链接: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
dotnet new web
settings.json
{ "ConnectionStrings":{ "DefaultConnection":"Server=...;Database=...;" }}
Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration(configureDelegate=>{ configureDelegate.AddJsonFile("settings.json"); }) .UseStartup<Startup>();
Startup.cs
using Microsoft.Extensions.Configuration;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
app.Run(async (context) => { // await context.Response.WriteAsync("Hello World!"); // JsonFile await context.Response.WriteAsync(configuration["ConnectionStrings:DefaultConnection"]); }); }
启动HelloCore,输出结果
Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration(configureDelegate => { //configureDelegate.AddJsonFile("settings.json"); configureDelegate.AddCommandLine(args); }) //.UseUrls("http://localhost:5001") .UseStartup<Startup>();
Startup.cs
app.Run(async (context) => { // await context.Response.WriteAsync("Hello World!"); // JsonFile //await context.Response.WriteAsync(configuration["ConnectionStrings:DefaultConnection"]); // CommandLine await context.Response.WriteAsync($"name={configuration["name"]}"); });
设置应用程序参数
启动HelloCore,输出结果
任务25:IHostEnvironment和 IApplicationLifetime介绍
Startup.cs
app.Run(async (context) => { await context.Response.WriteAsync($"ContentRootPath = {env.ContentRootPath}"); await context.Response.WriteAsync($"EnvironmentName = {env.EnvironmentName}"); await context.Response.WriteAsync($"WebRootPath = {env.WebRootPath}"); });
启动HelloCore,输出结果
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration, IApplicationLifetime applicationLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
applicationLifetime.ApplicationStarted.Register(() => { Console.WriteLine("Started"); });
applicationLifetime.ApplicationStopped.Register(() => { Console.WriteLine("Stopped"); });
applicationLifetime.ApplicationStopped.Register(() => { Console.WriteLine("Stopped"); });
app.Run(async (context) => { await context.Response.WriteAsync($"ContentRootPath = {env.ContentRootPath}"); await context.Response.WriteAsync($"EnvironmentName = {env.EnvironmentName}"); await context.Response.WriteAsync($"WebRootPath = {env.WebRootPath}"); }); }
启动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
dotnet new web --name HelloCore
F5 Start Debug
在csproj 的 ItemGroup 添加引用
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
New Terminal
dotnet restoredotnet watch run
修改代码保存后会自动重启
浏览器刷新即可看到更新结果
attach到进程调试
任务27:Middleware管道介绍
1.Middleware 与管道的概念
2.用 Middleware 来组成管道实践
3.管道的实现机制(RequestDelegate 与 ApplicationBuilder)
startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
// 添加一个中间件,传一个名字为next的request delegate app.Use(async (context,next)=>{ await context.Response.WriteAsync("1: before start..."); await next.Invoke(); });
// 接收一个RequestDelegate,返回一个RequestDelegate app.Use(next=>{ return (context)=>{ context.Response.WriteAsync("2: in the middle of start.."); return next(context); }; });
app.Run(async (context) => { await context.Response.WriteAsync("3: start..."); }); }
启动项目,输出结果
// 如果不调用next,则管道终止,不会输出"3: start..." app.Use(next=>{ return (context)=>{ return context.Response.WriteAsync("2: in the middle of start.."); //return next(context); }; });
// 使用Map构建路由,通过localhost:5000/task访问 app.Map("/task", taskApp=>{ taskApp.Run(async context=>{ await context.Response.WriteAsync("this is a task"); }); });
// 添加一个中间件,传一个名字为next的request delegate app.Use(async (context,next)=>{ await context.Response.WriteAsync("1: before start..."); await next.Invoke(); });
// 接收一个RequestDelegate,返回一个RequestDelegate // 如果不调用next,则管道终止,不会输出"3: start..." app.Use(next=>{ return (context)=>{ context.Response.WriteAsync("2: in the middle of start.."); return next(context); }; });
app.Run(async (context) => { await context.Response.WriteAsync("3: start..."); });
访问 https://localhost:5001/task
任务28:RequestDelegate管道实现思路
1.RequestDelegate
2.ApplicationBuilder:多个RequestDelegate拼接
// 添加一个中间件,传一个名字为next的RequestDelegateapp.Use(async (context,next)=>{ await context.Response.WriteAsync("1: before start...");// 完成自己处理 await next.Invoke();// 调用下一步});
// 封装一个function交给ApplicationBuilder处理app.Use(next=>{ return (context)=>{ context.Response.WriteAsync("2: in the middle of start.."); return next(context); };});
任务29:自己动手构建RequestDelegate管道
新建一个控制台程序
dotnet new console --name MyPipeline
新建一个类RequestDelegate.cs
using System;using System.Threading.Tasks;
namespace MyPipeline{ public delegate Task RequestDelegate(Context context);}
新建一个类Context.cs
using System;using System.Threading.Tasks;
namespace MyPipeline{ public class Context {
}}
using System;using System.Collections.Generic;using System.Threading.Tasks;
namespace MyPipeline{ class Program { public static List<Func<RequestDelegate,RequestDelegate>> _list = new List<Func<RequestDelegate, RequestDelegate>>(); static void Main(string[] args) { Use(next=>{ return context=>{ Console.WriteLine("1"); return next.Invoke(context); }; });
Use(next=>{ return context=>{ Console.WriteLine("2"); return next.Invoke(context); }; });
RequestDelegate end = (Context)=>{ Console.WriteLine("end..."); return Task.CompletedTask; };
_list.Reverse(); foreach(var middleware in _list) { end = middleware.Invoke(end); }
end.Invoke(new Context()); Console.ReadLine(); }
public static void Use(Func<RequestDelegate,RequestDelegate> middleware) { _list.Add(middleware); } }}
在任何一个Middleware可以结束管道
Use(next=>{ return context=>{ Console.WriteLine("1"); //return next.Invoke(context); return Task.CompletedTask;// 结束管道调用,只输出1 }; });
任务30:RoutingMiddleware介绍以及MVC引入
using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;
namespace HelloCore{ 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.AddRouting();// 添加依赖注入配置 }
// 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(); }
if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
// 通过localhost:5000/action访问 app.UseRouter(builder=>builder.MapGet("action", async context=>{ await context.Response.WriteAsync("this is a action"); }));
// 使用Map构建路由,通过localhost:5000/task访问 app.Map("/task", taskApp=>{ taskApp.Run(async context=>{ await context.Response.WriteAsync("this is a task"); }); });
// 添加一个中间件,传一个名字为next的request delegate app.Use(async (context,next)=>{ await context.Response.WriteAsync("1: before start..."); await next.Invoke(); });
// 如果不调用next,则管道终止,不会输出"3: start..." app.Use(next=>{ return (context)=>{ return context.Response.WriteAsync("2: in the middle of start.."); //return next(context); }; });
app.Run(async (context) => { await context.Response.WriteAsync("3: start..."); }); } }}
访问 https://localhost:5001/action
使用UseRouter方法2
using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;
namespace HelloCore{ 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.AddRouting();// 添加依赖注入配置 }
// 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(); }
if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
// 使用UseRouter方法2 // 通过localhost:5000/action访问 RequestDelegate handler = context=>context.Response.WriteAsync("this is a action"); var route = new Route( new RouteHandler(handler), "action", app.ApplicationServices.GetRequiredService<IInlineConstraintResolver>() );
app.UseRouter(route);
// 使用UseRouter方法1 // 通过localhost:5000/action访问 app.UseRouter(builder=>builder.MapGet("action", async context=>{ await context.Response.WriteAsync("this is a action"); }));
// 使用Map构建路由,通过localhost:5000/task访问 app.Map("/task", taskApp=>{ taskApp.Run(async context=>{ await context.Response.WriteAsync("this is a task"); }); });
// 添加一个中间件,传一个名字为next的request delegate app.Use(async (context,next)=>{ await context.Response.WriteAsync("1: before start..."); await next.Invoke(); });
// 如果不调用next,则管道终止,不会输出"3: start..." app.Use(next=>{ return (context)=>{ return context.Response.WriteAsync("2: in the middle of start.."); //return next(context); }; });
app.Run(async (context) => { await context.Response.WriteAsync("3: start..."); }); } }}
访问 https://localhost:5001/action
RountingMiddleware介绍
var routeHandler = new RouteHandler(context=>context.Response.WriteAsync("test"));
var route = new Route(routeHandler);
new RouteMiddleware(route)
RouteMiddleware.Invoke(httpContext)
_route.RouteAsync(context)
routeMatch(RouteContext)
OnRouteMatched(RouteContext)
点“在看”给我一朵小黄花
ASP.NET Core快速入门(第4章:ASP.NET Core HTTP介绍)--学习笔记相关推荐
- 《ASP.NET 1.1入门经典—— VISUAL C# .NET 2003编程篇》学习笔记和心得 - 第十章
第十章 ASP.NET服务器控件 ◆ Hyperlink的visiable属性可以显示或隐藏控件,这是一个非常有用的技巧,这点就比<a></a>有用呢! ◆ HTML中< ...
- 【笔记目录1】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
当前标签: ASP.NET Core快速入门 共2页: 1 2 下一页 任务50:Identity MVC:DbContextSeed初始化 GASA 2019-03-02 14:09 阅读:16 ...
- .NET Core快速入门教程 2、我的第一个.NET Core App(Windows篇)
一.前言 本篇开发环境? 1.操作系统: Windows 10 X64 2.SDK: .NET Core 2.0 Preview 二.安装 .NET Core SDK 1.下载 .NET Core 下 ...
- .NET Core快速入门教程 3、我的第一个.NET Core App (CentOS篇)
一.前言 本篇开发环境? 1.操作系统:CentOS7(因为ken比较偏爱CentOS7) 2.SDK版本:.NET Core 2.0 Preview 你可能需要的前置知识 1.了解如何通过Hyper ...
- .NET Core快速入门教程 5、使用VS Code进行C#代码调试的技巧
.NET Core 快速入门教程 .NET Core 快速学习.入门系列教程.这个入门系列教程主要跟大家聊聊.NET Core的前世今生,以及Windows.Linux(CentOS.Ubuntu)基 ...
- .NET Core快速入门教程 4、使用VS Code开发.NET Core控制台应用程序
一.前言 为什么选择VS Code? VS Code 是一款跨平台的代码编辑器,想想他的哥哥VS,并是微软出品的宇宙第一IDE, 那作为VS的弟弟,VS Code 也不会差,毕竟微软出品.反正ken是 ...
- 【番外篇】ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
- ASP.NET MVC3 快速入门
第一节 概述 (2011-02-23 20:57:18) 转载 标签: web应用程序 分类: ASP.NETMVC3 1.1 本教程的学习内容 在本教程中,你将学会如下内容: • ...
- Hadoop快速入门——第三章、MapReduce案例(字符统计)
Hadoop快速入门--第三章.MapReduce案例 目录 环境要求: 1.项目创建: 2.修改Maven 3.编码 4.本地文件测试 5.修改[Action]文件(修改测试文件路径) 6.导出ja ...
- MyBatis快速入门——第三章、DML语句操作
MyBatis快速入门--第三章.DML语句操作 目录 在接口类中添加[UsersMapper.java] 修改[com.item.mapper.UsersMapper.] [action.java] ...
最新文章
- python学习费用-学习老男孩python多少钱?收费贵不贵?
- RTSP流媒体数据传输的两种方式(TCP和UDP)
- 打印杨辉三角--for循环
- POJ 3617 Best Cow Line 贪心算法
- android v4包自动导入吧,android如何导入v4包的源码
- laravel的一些笔记
- python中的isinstance()使用方法[探索2]
- totolink服务器未响应,WiFi效果差的罪魁祸首竟然是这个 TOTOLINK为你深度讲解
- Ibatis.Net 数据库操作(四)
- 计算机考研数据结构参考书,2020考研计算机备考:数据结构参考书及重点
- android fsck,android fsck_msdos分析(一)
- 投诉百度快照对排名的影响
- 【Web】HTML基础——了解HMTL基本结构+常用标签的使用
- 10月10日第壹简报,星期一,农历九月十五
- 【无标题】水泥稳定层施工
- 首份财报营收增长扭亏为盈,为何怪兽充电的出路依旧“迷雾重重”
- 计算机科学丛书20周年——20本跨世经典 夯筑科技基石
- 尼龙毛柱分离T细胞法操作指南
- CSS 让背景图片全部显示,填满父div
- Java 小数点计算和四舍五入保留两位数
热门文章
- 将字符串中的大写字母变成小写字母
- head rush ajax chapter4 DOM
- 计算机突然蓝屏无法启动_为什么计算机无法立即启动?
- ea 备份码是什么_EA的原始访问是什么,值得吗?
- ios beta 下载_如何回滚到iOS 10(如果您使用的是iOS 11 Beta)
- ES6实用方法Object.assign、defineProperty、Symbol
- 从零开始编写自己的C#框架(14)——T4模板在逻辑层中的应用(三)
- 《面向对象的思考过程(原书第4版)》一1.11 组合
- 电脑内部录音教程Virtual Audio Cable使用教程
- Angularjs调用公共方法与共享数据