想在 ASP.NET Core 中间件(Middleware)中执行一个返回 ViewResult 的 MVC Controller Action ,请问如何实现?
通过下面的代码实现了
public class MvcHandlerMiddleware
{
private readonly RequestDelegate _next;
public MvcHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext, IServiceProvider serviceProvider)
{
if (httpContext.Request.Path == "/mvchandler")
{
var app = new ApplicationBuilder(serviceProvider);
app.UseMvc(routes =>
{
routes.MapRoute(
"mvchandler",
"mvchandler",
new { Controller = "Home", Action = "Index" });
});
app.Build().Invoke(httpContext);
return Task.CompletedTask;
}
return _next(httpContext);
}
}