从自定义中间件调用控制器和操作

5
我对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);
        }
    }
}

我该如何在我的中间件类中实现这个功能?


为什么不让路由引擎完成它的工作,使用属性路由将请求路由到您所需的控制器? - Henk Mollema
@HenkMollema 主要是为了学习目的。我只想知道如何从中间件动态创建路由。当我想从另一个程序集/类库加载控制器时,这可能会很方便。比如从一个具有自己中间件和控制器类的类库中。 - Vivendi
你可以创建一个重定向响应。 - Bart Calixto
2个回答

1

我认为实现自己的IRouter是一种方法。以下是我作为测试编写的自定义RouteHandler代码,对我来说效果良好。

  1. Added MvcRouteHandler and MvcApplicationBuilderExtensions in my project.

  2. Used Mynamespace.MvcRouteHandler in UseMvc method of MvcApplicationBuilderExtensions and renamed the method to 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. In Startup.cs, changed app.UseMvc to app.UseMyMvc

  4. Then in RouteAsync method of MyNamespace.MvcRouteHandler, set controller and action based on custom logic.

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接