3

When working with Katana Project we deal a lot with middlewares. On ASP.NET website they say

As previously mentioned, when the server accepts a request from a client, it is responsible for passing it through a pipeline of OWIN components, which are specified by the developer’s startup code. These pipeline components are known as middleware.

That's fine but I quite don't get it. At first I thought that middlewares were the ASP.NET components like WebAPI, SignalR and all of that. However, when studying authentication I saw the Cookie Authentication Middleware. This one is not an entire framework like WebAPI so it doesn't fit my initial idea of middleware.

So what Katana middlewares really are? They are just pieces of code that can be integrated on the execution pipeline and do work on the environment dictionary? And so, they can be simple components like an authentication middleware or interfaces to communicate with entire frameworks like WebAPI?

4

2 回答 2

6

中间件就像考虑数学函数组合一样简单。OWIN (几乎)规范的签名Func<AppFunc, AppFunc>,其中using AppFunc = Func<IDictionary<string, object>, Task>.

如果从功能组合的角度考虑,目的就很明确了:

val f : int -> int
let f x = x*x

val g : int -> int
let g x = x+x

您可以手动调用这些:

val result1 : int -> int
let result1 x = g(f(x))

或者你可以组合函数来创建一个新函数:

val result1 : int -> int
let newFunc = g • f
// or in F#
let newFunc = g << f

回到 OWIN,再次使用 F# 符号来保持简单:

type AppFunc = IDictionary<string, obj> -> Task
val app : AppFunc
val middleware : AppFunc -> AppFunc

应用 my apptomiddleware创建一个新的app'

let app' : AppFunc = middleware app

一个具体的例子是日志中间件。合成之后,你会发现请求的流程是这样的:

request -> loggingMiddleware -> app -> loggingMiddleware -> response

让您有机会记录传入的请求和传出的响应。这实际上与 Web API 的HttpMessageHandler.

Katana 通过IAppBuilder.Use扩展以及每个公开快捷扩展方法的中间件库(例如.UseWebApi.UseSignalR.

此外,Katana 使用中间件挂载框架,以便它可以使用基于 404 响应状态代码的故障机制来尝试使用另一个框架处理请求。您可以通过在不同路径上安装框架来以不同方式处理此问题,但如果您想使用不同框架在统一路径下处理应用程序的不同部分,则此机制效果很好。

于 2014-09-25T16:33:58.600 回答
2

如果您熟悉 ASP.NET 应用程序生命周期及其处理管道,

http://www.iis.net/learn/application-frameworks/building-and-running-aspnet-applications/how-to-take-advantage-of-the-iis-integrated-pipeline

您可能对什么是中间件有一些基本的了解。管道本身(主要是 System.Web 中的类型)是一个中间件,它将您的 ASP.NET 应用程序(WebForms、MVC)桥接到底层主机(Web 服务器,例如 IIS、IIS Express、Cassini、selfhost 等)。

然而,经典的 System.Web 是高度耦合的,然后是 OWIN 和 Katana。如果您深入研究 Katana 的代码库,您会发现它本身就是一个管道。它更加灵活且高度可定制,因此将其称为中间件现在比以往任何时候都更加简洁。

ASP.NET vNext 完全摆脱了 System.Web,这样你就可以看到 Katana 在接下来的几个月里如何发挥重要作用。

于 2014-05-20T12:56:54.827 回答