2015-08-27 99 views
4

我是ASP.NET 5和中間件類的新手。我想創建的是一個讀取傳入URL請求的中間件類。基於此,我要麼讓它通過並執行正常的路徑查找,要麼我希望我的中間件類從我的Web API類調用特定的控制器/操作。來自定製中間件的呼叫控制器和操作

我現在擁有的是以下內容。我認爲代碼中的評論解釋了我試圖達到的目標。

public class RouteMiddleware 
{ 
    private readonly RequestDelegate _next; 

    public RouteMiddleware(RequestDelegate next) 
    { 
     _next = next; 
    } 

    public async Task Invoke(HttpContext httpContext) 
    { 
     if(httpContext.Request.QueryString.Value == "test") 
     { 
      // Call custom Controller/Action 
      // Then, don't do any more route resolving, since we already have the right controller/action 
     } 
     else 
     { 
      // Continue like normal 
      await _next.Invoke(httpContext); 
     } 
    } 
} 

我該如何在我的中間件類中做到這一點?

+0

爲什麼不讓路由引擎它的工作讓它請求路由到您想要使用控制器屬性的路由? –

+0

@HenkMollema主要用於學習目的。我只想知道如何從中間件動態創建路由。當我想從另一個彙編/類庫中加載控制器時可以派上用場。就像擁有自己的中間件和控制器類的類庫一樣。 – Vivendi

+0

你可以創建一個重定向響應。 –

回答

0

我想這樣做的一個方法是通過自己實現IRouter的。 下面是我做了一個測試,以獲得自己的RouteHandler,它對我來說很好。

  1. 新增MvcRouteHandler並在我的項目MvcApplicationBuilderExtensions

  2. MvcApplicationBuilderExtensionsUseMvc方法用於Mynamespace.MvcRouteHandler並改名爲法UseMyMvc

    public static IApplicationBuilder UseMyMvc(this IApplicationBuilder app,Action<IRouteBuilder> configureRoutes) 
        { 
         MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices); 
         var routes = new RouteBuilder 
         { 
          DefaultHandler = new MyNamespace.MvcRouteHandler(), 
          ServiceProvider = app.ApplicationServices 
         }; 
        //..... rest of the code of this method here... 
        } 
    
  3. 在Startup.cs,如果是的MyNamespace.MvcRouteHandlerRouteAsync方法的基礎上,定製邏輯設置控制​​器和動作改變app.UseMvcapp.UseMyMvc

  4. context.RouteData.Values["area"] = "MyArea"; 
        context.RouteData.Values["controller"] = "MyController"; 
        context.RouteData.Values["action"] = "MyAction";