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 restore
dotnet 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的RequestDelegate
app.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)
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。
如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。
ASP.NET Core快速入门(第4章:ASP.NET Core HTTP介绍)--学习笔记的更多相关文章
- ASP.NET Core 快速入门(Razor Pages + Entity Framework Core)
引子 自从 2009 年开始在博客园写文章,这是目前我写的最长的一篇文章了. 前前后后,我总共花了 5 天的时间,每天超过 3 小时不间断写作和代码调试.总共有 8 篇文章,每篇 5~6 个小结,总截 ...
- ASP.NET Core快速入门--学习笔记系列文章索引目录
课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 抓住国庆假期的尾巴完成了此系列课程的学习笔记输出! ASP.NET Core快 ...
- 【笔记目录2】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
当前标签: ASP.NET Core快速入门 共2页: 上一页 1 2 任务27:Middleware管道介绍 GASA 2019-02-12 20:07 阅读:15 评论:0 任务26:dotne ...
- 【笔记目录1】【jessetalk 】ASP.NET Core快速入门_学习笔记汇总
当前标签: ASP.NET Core快速入门 共2页: 1 2 下一页 任务50:Identity MVC:DbContextSeed初始化 GASA 2019-03-02 14:09 阅读:16 ...
- 【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
- 【第一篇】ASP.NET MVC快速入门之数据库操作(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
- .NET Core 快速入门教程
.NET Core 快速学习.入门系列教程.这个入门系列教程主要跟大家聊聊.NET Core的前世今生,以及Windows.Linux(CentOS.Ubuntu)基础开发环境的搭建.第一个.NET ...
- .NET Core快速入门教程 2、我的第一个.NET Core App(Windows篇)
一.前言 本篇开发环境?1.操作系统: Windows 10 X642.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-V安 ...
- 【第二篇】ASP.NET MVC快速入门之数据注解(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
随机推荐
- python基础(29):网络编程(软件开发架构、网络基础、套接字初使用)
1. 软件开发架构 我们了解的程序之间通讯的应用可分为两种: 第一种是应用类:qq.微信.百度网盘.腾讯视频这一类是属于需要安装的桌面应用. 第二种是web类:比如百度.知乎.博客园等使用浏览器访问就 ...
- 调用大漠插件发送QQ和微信消息 C#版
大漠插件:3.1233 找图,找色,识字,找字,窗口,按鼠标,按键盘 0.注册dm.dll: regsvr32 xxx\dm.dll 1.添加com引用: 2.dmsoft各种调用: 原理: 查找窗口 ...
- JS基础语法---数组案例---9个练习
练习1:求数组中所有元素的和 var arr1 = [10, 20, 30, 40, 50]; var sum = 0; for (var i = 0; i < arr1.length; i++ ...
- ECAMScript中的let和const
let与const命令都是用来在js中声明变量的,在使用上与var相似,但存在一些区别,下面先讲let同var的区别 let 怎么使用呢,同var一样,let 变量名 就可以声明了 区别一:其作 ...
- EGit(Git Eclipse Plugin)使用
https://shihlei.iteye.com/blog/2124411 前言: 1)Git于SVN的不同 Git是分布式数据库,本地创建仓库,即可在本地完成版本控制(等价于SVN在本地 ...
- python中的随机模块random
random模块是 python 中为随机数所使用的模块 ```import random # 随机生成0-1范围内的随机浮点数i = random.random()print(i) # 随机生成范围 ...
- 内置模块:time, datetime, random, json, pickle, os, sys, hashlib, collections, re
1.time模块 import time time.time() # 时间戳 浮点数 time.sleep() # 睡眠 time.gmtime()/time.localtime() #结构化时间 数 ...
- CodeForces - 1256D (贪心+思维)
题意 给定一个长度为n的二进制串(即由n个'0'和'1'构成的字符串),你最多可以进行k次交换相邻两个字符的操作,求字典序最小的串. 思路 大致就是找0的位置,然后贪心的放到最前面,这样字典序会最小: ...
- mysql清空带外键的表
set FOREIGN_KEY_CHECKS =0;TRUNCATE memo;TRUNCATE customer;set FOREIGN_KEY_CHECKS =1;
- LeetCode 动态规划
动态规划:适用于子问题不是独立的情况,也就是各子问题包含子子问题,若用分治算法,则会做很多不必要的工作,重复的求解子问题,动态规划对每个子子问题,只求解一次将其结果保存在一张表中,从而避免重复计算. ...