Startup配置类 居然又是约定

Microsoft.Owin.Host.SystemWeb

  这个dll可以让OWin接管IIS的请求,虽然同样是托管在IIS,但是所有的请求都会被OWin来处理。在OWin的4层结构中(Applicaton->Middleware->Server->Host),Microsoft.Owin.Host.SystemWeb属于Server层,还有一个同样也在Server层的是Microsoft.Owin.Host.HttpListener,这个可以实现利用控制台程序现实自托管,就可以完全摆脱IIS了。

Startup配置类

  要使用Owin的应用程序都要有一个叫Startup的类,在这个类里面有一个Configuration的方法,这两个名字是默认约定,必须用同样的名字才会被Owin找到。你也可以用Attribute和在web.config文件中配置的方式来定义这个类,详情见Startup。我们在Configuration方法里面,就可以定义我们自己的管道了。我们可以通过Use来添加自己的管道的处理步骤,并且可以自己设置处理顺序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void Configuration(IAppBuilder app)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync(" Authentication... ");
        await next();
    });
 
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Authorization... ");
        await next();
    });
 
    app.Use(async (context, next) =>
    {
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync("Hello World!");
    });
}

  我们需要在web.config中加入一个配置,让OWin处理所有的请求:

1
2
3
<appSettings>
  <add key="owin:HandleAllRequests" value="true"/>
</appSettings>

  这样的话,不管我们输入什么URL,都会返回同样的结果,因为不管哪个URL,对应的都是我们上面所写的代码。

posted @ 2015-11-25 15:12  左立军  阅读(735)  评论(0编辑  收藏  举报