public class HelloMiddleware : OwinMiddleware
{
//實例化中間件與(可選的)指向下一個組件的指針。
public HelloMiddleware(OwinMiddleware next) : base(next)
{
}
//注意看,這個方法的返回值是Task,這其實是一個信號,告訴我們可以使用async去修飾,將方法設置為異步方法.
public override Task Invoke(IOwinContext context)
{
//do something when invode
throw new NotImplementedException();
}
}
嘗試著改造一下這個類.請在程序集中引入Json.NET 還有Microsoft.Owin
public class HelloMiddleware : OwinMiddleware
{
//實例化中間件與(可選的)指向下一個組件的指針。
public HelloMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
if (!IsHelloRequest(context))//過濾不屬于這個中間件處理的Http請求
{
await Next.Invoke(context);//直接甩給Next節(jié)點處理.
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;
}
}
到這里一個中間件就寫完了.然后
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有關如何配置應用程序的詳細信息,請訪問 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>();//這里配置一下就可以用了.
}
}