首页 新闻 赞助 找找看

如何在 ASP.NET Core 中间件中执行 MVC Controller 中的 Action

0
悬赏园豆:30 [已解决问题] 解决于 2018-08-06 19:02

想在 ASP.NET Core 中间件(Middleware)中执行一个返回 ViewResult 的 MVC Controller Action ,请问如何实现?

dudu的主页 dudu | 高人七级 | 园豆:31075
提问于:2018-08-06 16:54
< >
分享
最佳答案
1

通过下面的代码实现了

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);
    }
}
dudu | 高人七级 |园豆:31075 | 2018-08-06 19:00
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册