【问题标题】:Call controller and action from custom middleware从自定义中间件调用控制器和操作
【发布时间】:2015-11-22 08:11:16
【问题描述】:

我是 ASP.NET 5 和中间件类的新手。我要创建的是一个读取传入 URL 请求的中间件类。基于此,我要么让它通过并进行正常的路由查找,要么我希望我的中间件类从我的 Web API 类调用特定的控制器/动作。

我目前拥有的是以下内容。我认为代码中的 cmets 解释了我想要实现的目标。

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);
        }
    }
}

如何在我的中间件类中做到这一点?

【问题讨论】:

  • 为什么不让路由引擎工作,让它使用属性路由将请求路由到您想要的控制器?
  • @HenkMollema 主要用于学习目的。我只想知道如何从中间件动态创建路由。当我想从另一个程序集/类库加载控制器时可以派上用场。就像来自具有自己的中间件和控制器类的类库一样。
  • 您可以创建重定向响应。

标签: c# asp.net-core middleware asp.net-core-mvc


【解决方案1】:

我认为这样做的一种方法是拥有自己的 IRouter 实现。 这是我为拥有自己的 RouteHandler 所做的测试,它对我来说效果很好。

  1. 在我的项目中添加了MvcRouteHandlerMvcApplicationBuilderExtensions

  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 中,将 app.UseMvc 更改为 app.UseMyMvc

  4. 然后在MyNamespace.MvcRouteHandlerRouteAsync方法中,根据自定义逻辑设置控制​​器和动作。

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

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多