【发布时间】: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