2017-09-08 43 views
1

後使用IAppBuilder.UseWebApi我有成功的是執行,直到有沒有更多的中間件類3中間件類。在調用中間件類之後,我不再需要將請求傳遞給路由器。如何OWIN中間件

這樣做的最好方法是什麼?

例如,我有這樣的代碼:

// Register middleware. Order is important! 
app.Use<Authentication>(); 
app.Use<Logging>(); 
app.Use<Example>(configExample); 

這可以作爲expected.On每個請求的第一Authentication運行,然後Logging,然後Example

而且我可以看到,在啓動程序,這些app.Use<>()行通過傳遞委託實例化合適的中間件。該代表包含一個屬性Target,該屬性指向要運行的下一個中間件類。由於顯而易見的原因,傳遞給Example類的代理是空的(因爲它是鏈中最後一箇中間件類)。

沒有在過去鏈中間件類改變代碼(我不希望爲了重要的),我怎麼可以調用路由器?我的路由器看起來是這樣的:

HttpConfiguration config = new HttpConfiguration(); 
config.Routes.MapHttpRoute(
    ... 
); 
config.Routes.MapHttpRoute(
    ... 
); 
etc. 
app.UseWebApi(config); 

我想一定是我的理解一些偉大的邏輯差距,因爲必須有結束中間件鏈

回答

0

的答案是,中間件傳遞一個合乎邏輯的方式當沒有更多中間件時自動發送給控制器。但是我在中間件中使用的代碼行阻止了這個教程。

我一直按照簡潔的方式在這裏創建中間件: https://www.codeproject.com/Articles/864725/ASP-NET-Understanding-OWIN-Katana-and-the-Middlewa

而這兩條線:

IOwinContext context = new OwinContext(environment); 
await context.Response.WriteAsync("<h1>Hello from Example " + _configExample + "</h1>"); 

導致來自控制器的響應被截斷(或其它)。這是代碼:

using System; 
using System.Collections.Generic; 
using System.Threading.Tasks; 

namespace Avesta.ASP.Middleware 
{ 
    using AppFunc = Func<IDictionary<string, object>, Task>; 

    public class Example 
    { 
     AppFunc _next; 
     string _configExample; 

     public Example(AppFunc next, string configExample) 
     { 
      _next = next; 
      _configExample = configExample; 
     } 

     public async Task Invoke(IDictionary<string, object> env) 
     { 
      //IOwinContext context = new OwinContext(environment); 
      //await context.Response.WriteAsync("<h1>Hello from Example " + _configExample + "</h1>"); 
      await _next.Invoke(env); 
     } 
    } 
}