public class HelloMiddleware : OwinMiddleware
{
//實(shí)例化中間件與(可選的)指向下一個(gè)組件的指針。
public HelloMiddleware(OwinMiddleware next) : base(next)
{
}
//注意看,這個(gè)方法的返回值是Task,這其實(shí)是一個(gè)信號,告訴我們可以使用async去修飾,將方法設(shè)置為異步方法.
public override Task Invoke(IOwinContext context)
{
//do something when invode
throw new NotImplementedException();
}
}
public class HelloMiddleware : OwinMiddleware
{
//實(shí)例化中間件與(可選的)指向下一個(gè)組件的指針。
public HelloMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
if (!IsHelloRequest(context))//過濾不屬于這個(gè)中間件處理的Http請求
{
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";
}
//過濾請求,只攔截特定Uri
private static bool IsHelloRequest(IOwinContext context)
{
return string.Compare(context.Request.Path.Value, "/$hello", StringComparison.OrdinalIgnoreCase) == 0;
}
}
到這里一個(gè)中間件就寫完了.然后
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有關(guān)如何配置應(yīng)用程序的詳細(xì)信息,請?jiān)L問 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>();//這里配置一下就可以用了.
}
}