前言

本篇文章介绍ASP.NET Core里,用来处理HTTP封包的Middleware,为自己留个纪录也希望能帮助到有需要的开发人员。

结构

  • 在ASP.NET Core里,每个从「浏览器传入」的HTTP Request封包,会被系统封装为「HttpRequest对象」,并且配置默认的HttpResponse对象、Session对象、ClaimsPrincipal对象...等等物件。接着将这些对象,封装成为一个「HttpContext对象」,用来提供ASP.NET Core后续使用。

  • ASP.NET Core在收到HttpContext之后,会把它交给一个「Pipeline」去处理。这个Pipeline里面配置很多「Middleware」。系统会将HttpContext,依序传递给Pipeline里的Middleware去处理。每个Middleware会依照自己内部的程序逻辑,来运算处理HttpContext,并且变更HttpContext所封装的对象内容。

  • ASP.NET Core在收到经由Middleware处理完毕的HttpContext之后,就会取出其中所封装的HttpResponse对象。然后依照这个HttpResponse对象,来建立从「服务器回传」的HTTP Response封包内容。

  • ASP.NET Core经由上述的系统结构,完成HTTP Request封包输入、HTTP Response封包输出的工作流程。

开发

Invoke

[ASP.NET Core] Getting Started这篇文章里,提供了一个ASP.NET Core的Middleware范例:HelloWorldMiddleware。在这个范例里,Middleware透过实做Invoke方法,来提供自己所封装的程序逻辑。

public class HelloWorldMiddleware
{
// Fields
private readonly RequestDelegate _next; // Constructors
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
} // Methods
public Task Invoke(HttpContext context)
{
// Response
context.Response.WriteAsync("Hello World!"); // Return
return Task.CompletedTask;
}
}

HttpContext.Request

在实做Middleware.Invoke方法的时候,开发人员可以透过HttpContext.Request,来取得从「浏览器传入」的HTTP Request封包内容。在下列的范例程序代码里,就是透过HttpContext.Request的Path、QueryString两个属性,来分别取得HTTP Request封包的URL路径与QueryString内容。

public class HelloWorldMiddleware
{
// Fields
private readonly RequestDelegate _next; // Constructors
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
} // Methods
public Task Invoke(HttpContext context)
{
// Request
string path = context.Request.Path.ToString();
string queryString = context.Request.QueryString.ToString();
string message = string.Format("path={0}, queryString={1}", path, queryString); // Response
context.Response.WriteAsync(message); // Return
return Task.CompletedTask;
}
}

HttpContext.Response

同样在实做Middleware.Invoke方法的时候,开发人员可以透过HttpContext.Response,来设定从「服务器回传」的HTTP Response封包内容。在下列的范例程序代码里,就是透过HttpContext.Response的WriteAsync方法、StatusCode属性,来分别设定HTTP Response封包的Content与StatusCode。

public class HelloWorldMiddleware
{
// Fields
private readonly RequestDelegate _next; // Constructors
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
} // Methods
public Task Invoke(HttpContext context)
{
// Response
context.Response.StatusCode = 404;
context.Response.WriteAsync("Not Found"); // Return
return Task.CompletedTask;
}
}

Exception

而在实做Middleware.Invoke方法的时候,如果程序代码里发生了预期之外的Exception。ASP.NET Core预设会使用「500 Internal Server Error」,这个StatusCode来通报系统内部发生异常。 在下列的范例程序代码里,就是直接抛出一个例外错误,交由ASP.NET Core的错误处理机制去处理。

public class HelloWorldMiddleware
{
// Fields
private readonly RequestDelegate _next; // Constructors
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
} // Methods
public Task Invoke(HttpContext context)
{
// Exception
throw new Exception(); // Return
return Task.CompletedTask;
}
}

RequestDelegate

建立Middleware的时候,开发人员可以透过建构子所传入的RequestDelegate,来参考到Pipeline里的下一个Middleware。透过调用RequestDelegate,就可以调用Pipeline里的下一个Middleware的Invoke方法。在下列的范例程序代码里,就是透过调用RequestDelegate,来调用Pipeline里的下一个Middleware的Invoke方法,藉此串接其他Middleware的程序逻辑。

public class HelloWorldMiddleware
{
// Fields
private readonly RequestDelegate _next; // Constructors
public HelloWorldMiddleware(RequestDelegate next)
{
_next = next;
} // Methods
public async Task Invoke(HttpContext context)
{
// Do Something 01
//.... // Next
await _next.Invoke(context); // Do Something 02
// ...
}
}

参考

[ASP.NET Core] Middleware的更多相关文章

  1. ASP.NET Core Middleware 抽丝剥茧

    一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道pipeline中用于处理请求和操作响应的组件. 每个组件是pipeline 中的一环. 自行决定是否将请求传递给下一 ...

  2. ASP.NET Core Middleware (转载)

    What is Middleware? Put simply, you use middleware components to compose the functionality of your A ...

  3. Prerender Application Level Middleware - ASP.NET Core Middleware

    In the previous post Use Prerender to improve AngularJS SEO, I have explained different solutions at ...

  4. ASP.NET Core Middleware管道介绍

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.Use(async (context, ne ...

  5. 翻译 - ASP.NET Core 基本知识 - 中间件(Middleware)

    翻译自 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0 中间件是集成 ...

  6. [转]Publishing and Running ASP.NET Core Applications with IIS

    本文转自:https://weblog.west-wind.com/posts/2016/Jun/06/Publishing-and-Running-ASPNET-Core-Applications- ...

  7. 如何一秒钟从头构建一个 ASP.NET Core 中间件

    前言 其实地上本没有路,走的人多了,也便成了路. -- 鲁迅 就像上面鲁迅说的那样,其实在我们开发中间件的过程中,微软并没有制定一些策略或者文档来约束你如何编写一个中间件程序, 但是其中却存在者一些最 ...

  8. 极简版ASP.NET Core学习路径及教程

    绝承认这是一个七天速成教程,即使有这个效果,我也不愿意接受这个名字.嗯. 这个路径分为两块: 实践入门 理论延伸 有了ASP.NET以及C#的知识以及项目经验,我们几乎可以不再需要了解任何新的知识就开 ...

  9. asp.net core中写入自定义中间件

    首先要明确什么是中间件?微软官方解释:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?tabs=aspnet ...

随机推荐

  1. 模拟ajax的 script请求

    /** * 模拟ajax的 script请求 * @param {[type]} options [description] * @return {[type]} [description] */ f ...

  2. 用扩展开发一个PHP类

    原文:http://my.oschina.net/mickelfeng/blog/122519?p=1 假设我们要用PHP扩展实 现一个类Person,它有一个private的成员变量$_name和两 ...

  3. JAVA基础代码分享--学生成绩管理

    问题描述: 从键盘读入学生成绩,找出最高分,并输出学生成绩等级. 成绩>=最高分-10  等级为’A’   成绩>=最高分-20  等级为’B’ 成绩>=最高分-30  等级为’C’ ...

  4. 机器学习基础——梯度下降法(Gradient Descent)

    机器学习基础--梯度下降法(Gradient Descent) 看了coursea的机器学习课,知道了梯度下降法.一开始只是对其做了下简单的了解.随着内容的深入,发现梯度下降法在很多算法中都用的到,除 ...

  5. new的探究

    new操作符易用,但是往往容易忽略对其的理解. var foo= new Foo(); 这个简单的语句,涉及到了一系列的步骤: 1),给对象开辟内存,即 var foo= {}; 2),修改新对象的隐 ...

  6. JS去除空格方法记录

    JS中去掉空格 //去除空格  String.prototype.Trim = function() {      return this.replace(/\s+/g, ""); ...

  7. 关于JavaScript预编译和执行顺序以及函数引用类型的思考

    昨晚在对项目中的一部分做模块化处理的时候,遇到了一个问题,一个重新定义的function对一个通用类中的function进行赋值覆盖的时候,失败了.问题抽象出来是这样的: <script > ...

  8. SQLServer学习笔记系列11

    一.写在前面的话 身体是革命的本钱,这句放在嘴边常说的话,还是拿出来一起共勉,提醒一起奋斗的同僚们,保证睡眠,注意身体!偶尔加个班,也许不曾感觉到身体发出的讯号,长期晚睡真心扛不住!自己也制定计划,敦 ...

  9. PR&AE插件开发遇到的一个坑

    经过一段时间的摸索,对Adobe Premiere Pro和After Effects系列插件的开发工作有了一定的掌握.如今公司需要针对Premiere Pro和After Effects开发另外一款 ...

  10. WCF服务自我寄宿 Windows服务

    WCF寄宿有自我寄宿跟IIS寄宿 服务代码: [ServiceContract] ---服务契约 public interface ICustomerService { [OperationContr ...