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)

点“在看”给我一朵小黄花

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/312918.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java使用JWS API开发Web Service

JAX-WS&#xff0c;即Java API for XML Web Service&#xff0c;是Java开发基于SOAP协议的Web Service的标准。使用JWS API就可以直接开发简单的Web Service应用。 一、创建Web Service 打开Eclipse&#xff0c;新建一个Java Project&#xff0c;如下图所示&#xff1a; 新建了…

ASP.NET Core快速入门(第3章:依赖注入)--学习笔记

点击蓝字关注我们课程链接&#xff1a;http://video.jessetalk.cn/course/explore良心课程&#xff0c;大家一起来学习哈&#xff01;任务16&#xff1a;介绍1、依赖注入概念详解从UML和软件建模来理解从单元测试来理解2、ASP.NET Core 源码解析任务17&#xff1a;从UML角度来理…

使用wsimport命令创建Web Service客户端

一、wsimport简介 在jdk的bin文件夹中&#xff0c;有一个wsimport.exe工具。这个工具可以依据Web Service的描述文件wsdl生成相应的类文件&#xff0c;然后用这些类文件&#xff0c;被Web Service的客户端导入之后&#xff0c;就可以像调用本地的类一样调用WebService提供的方法…

读《持续交付2.0》

几年前看过《持续交付(发布可靠软件的系统方法)》&#xff0c;感触不是很深&#xff0c;最近看了这本书的译者乔梁编写的《持续交付2.0》&#xff0c;结合工作中的种种&#xff0c;又有一种相见恨晚的感觉。可见好书是需要经常翻阅的&#xff0c;每次都会带来新的收获和思考。全…

Java使用Apache CXF开发Web Service

转自&#xff1a;http://blog.csdn.net/hu_shengyang/article/details/38384597 以前工作中也用CXF,但都是用别人现成搭好的环境&#xff0c;这次自己重头搭建一遍环境。过程中也有遇到的问题&#xff0c;也做了简单的整理。 对于CXF是干什么用的&#xff0c;我不想多说&#x…

程序员修神之路--kubernetes是微服务发展的必然产物

菜菜哥&#xff0c;我昨天又请假出去面试了战况如何呀&#xff1f;多数面试题回答的还行&#xff0c;但是最后让我介绍微服务和kubernetes的时候&#xff0c;挂了话说微服务和kubernetes内容确实挺多的那你给我大体介绍一下呗可以呀&#xff0c;不过要请和coffee哦◆◆kubernet…

.NET core3.0 使用Jwt保护api

摘要&#xff1a;本文演示如何向有效用户提供jwt&#xff0c;以及如何在webapi中使用该token通过JwtBearerMiddleware中间件对用户进行身份认证。认证和授权区别&#xff1f;首先我们要弄清楚认证&#xff08;Authentication&#xff09;和授权&#xff08;Authorization&#…

Java ArrayList的实现原理详解

ArrayList是Java List类型的集合类中最常使用的&#xff0c;本文基于Java1.8&#xff0c;对于ArrayList的实现原理做一下详细讲解。 &#xff08;Java1.8源码&#xff1a;http://docs.oracle.com/javase/8/docs/api/&#xff09; 一、ArrayList实现原理总结 ArrayList的实现原…

.NET开发者的机遇与Web Blazor基础(有彩蛋)

一.唠唠WebAssembly的发展历程目前有很多支持WebAssembly的项目&#xff0c;但发展最快的是Blazor&#xff0c;这是一个构建单页面的.NET技术&#xff0c;目前已经从Preview版本升级到了beta版本&#xff0c;微软计划在2020年5月发布Blazor的第一个版本。Blazor是什么&#xff…

Java LinkedList的实现原理详解

LinkedList是Java List类型的集合类的一种实现&#xff0c;此外&#xff0c;LinkedList还实现了Deque接口。本文基于Java1.8&#xff0c;对于LinkedList的实现原理做一下详细讲解。 &#xff08;Java1.8源码&#xff1a;http://docs.oracle.com/javase/8/docs/api/&#xff09…

知乎高赞:中国有哪些不错的开源软件产品?

点击蓝字“dotNET匠人”关注我哟加个“星标★”&#xff0c;每日 7:15&#xff0c;好文必达&#xff01;在知乎上&#xff0c;有个问题问“中国有什么拿得出手的开源软件产品&#xff08;在 GitHub 等社区受欢迎度较好的&#xff09;&#xff1f;”事实上&#xff0c;还不少呢~…

容器日志管理 (2) 开源日志管理方案 ELK/EFK

本篇已加入《.NET Core on K8S学习实践系列文章索引》&#xff0c;可以点击查看更多容器化技术相关系列文章。上一篇《容器日志管理&#xff08;1&#xff09;》中介绍了Docker自带的logs子命令以及其Logging driver&#xff0c;本篇将会介绍一个流行的开源日志管理方案ELK/EFK…

关于Scrum起源,读这一篇论文就足够啦!《新新产品开发游戏》

关于Scrum的起源&#xff0c;我们经常会提到1986年发表在HBR上的一篇论文&#xff0c;《The New New Product Development Game》&#xff0c;今天我们把它重新翻译&#xff0c;一起重温为何Scrum会如此设置3355&#xff1f;为何会用橄榄球的术语来代表Scrum&#xff1f;The Ne…

Java HashMap的实现原理详解

HashMap是Java Map类型的集合类中最常使用的&#xff0c;本文基于Java1.8&#xff0c;对于HashMap的实现原理做一下详细讲解。 &#xff08;Java1.8源码&#xff1a;http://docs.oracle.com/javase/8/docs/api/&#xff09; 一、HashMap实现原理总结 HashMap的实现原理总结如下…

ASP.NET Core快速入门(第5章:认证与授权)--学习笔记

点击蓝字关注我们课程链接&#xff1a;http://video.jessetalk.cn/course/explore良心课程&#xff0c;大家一起来学习哈&#xff01;任务31&#xff1a;课时介绍1.Cookie-based认证与授权2.Cookie-based认证实现3.Jwt认证与授权介绍4.Jwt认证与授权实现5.Jwt认证与授权6.Role …

Java HashSet的实现原理详解

HashSet是Java Map类型的集合类中最常使用的&#xff0c;本文基于Java1.8&#xff0c;对于HashSet的实现原理做一下详细讲解。 &#xff08;Java1.8源码&#xff1a;http://docs.oracle.com/javase/8/docs/api/&#xff09; 一、HashSet实现原理总结 HashSet的实现原理总结如下…

asp.net mvc 自定义 pager 封装与优化

asp.net mvc 自定义 pager 封装与优化Intro之前做了一个通用的分页组件&#xff0c;但是有些不足&#xff0c;从翻页事件和分页样式都融合在后台代码中&#xff0c;到翻页事件可以自定义&#xff0c;再到翻页和样式都和代码分离&#xff0c; 自定义分页 pager 越来越容易扩展了…

Java LinkedHashMap的实现原理详解

1. LinkedHashSet概述&#xff1a; LinkedHashSet是具有可预知迭代顺序的Set接口的哈希表和链接列表实现。此实现与HashSet的不同之处在于&#xff0c;后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序&#xff0c;该迭代顺序可为插入顺序或是访问顺序…

.net core 中通过 PostConfigure 验证 Options 参数

.net core 中通过 PostConfigure 验证 Options 参数Intro在 .net core 中配置项推荐用 Options 来实现&#xff0c;有一些参数可能必须是用由用户来配置&#xff0c;不能直接写成默认值的参数&#xff0c;这样就需要就 Options 中的参数做一些校验&#xff0c;否则程序内部可能…

Spring配置错误java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/TransactionAwareDataS

在对Spring数据源dataSource配置之后&#xff0c;运行程序出现如下错误&#xff1a; java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy 原因是项目没有导入spring-jdbc的jar包。 如果使用maven&#xff0c;可以直接在pom…