2015-08-27 59 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";