什么是OWIN中間件?
承接上篇,中間件的概念,前面已經(jīng)講過(guò)了,類似于HttpModule,用于對(duì)于管線做點(diǎn)什么是,比方說(shuō),過(guò)濾,分發(fā),日志.
如何寫(xiě)一個(gè)中間件?
繼承抽象類OwinMiddleware,通過(guò)IDE自動(dòng)override兩個(gè)方法.這時(shí)候,你的代碼如下:
public class HelloMiddleware : OwinMiddleware
{
//實(shí)例化中間件與(可選的)指向下一個(gè)組件的指針。
public HelloMiddleware(OwinMiddleware next) : base(next)
{
}
//注意看,這個(gè)方法的返回值是Task,這其實(shí)是一個(gè)信號(hào),告訴我們可以使用async去修飾,將方法設(shè)置為異步方法.
public override Task Invoke(IOwinContext context)
{
//do something when invode
throw new NotImplementedException();
}
}
嘗試著改造一下這個(gè)類.請(qǐng)?jiān)诔绦蚣幸隞son.NET 還有Microsoft.Owin
public class HelloMiddleware : OwinMiddleware
{
//實(shí)例化中間件與(可選的)指向下一個(gè)組件的指針。
public HelloMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
if (!IsHelloRequest(context))//過(guò)濾不屬于這個(gè)中間件處理的Http請(qǐng)求
{
await Next.Invoke(context);//直接甩給Next節(jié)點(diǎn)處理.
return;
}
var helloInfo = new { name = "songtin.huang", description = "Fa~Q", message = "Hello" };
var json = JsonConvert.SerializeObject(helloInfo, new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
context.Response.Write(json);
context.Response.ContentType = "application/json;charset=utf-8";
}
//過(guò)濾請(qǐng)求,只攔截特定Uri
private static bool IsHelloRequest(IOwinContext context)
{
return string.Compare(context.Request.Path.Value, "/$hello", StringComparison.OrdinalIgnoreCase) == 0;
}
}
到這里一個(gè)中間件就寫(xiě)完了.然后
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有關(guān)如何配置應(yīng)用程序的詳細(xì)信息,請(qǐng)?jiān)L問(wèn) http://go.microsoft.com/fwlink/?LinkID=316888
var config = new HttpConfiguration();
config.Services.Replace(typeof(IContentNegotiator), new JsonFirstContentNegotiator());
app.UseWebApi(config);
app.Use<HelloMiddleware.HelloMiddleware>();//這里配置一下就可以用了.
}
}
F5啟動(dòng),然后在瀏覽器url上,加上/$hello,應(yīng)該就能看到j(luò)son格式的我的問(wèn)候...祝你好運(yùn)