代码之家  ›  专栏  ›  技术社区  ›  Roman Pokrovskij Archil Labadze

如何用RazorPages路由替换MVC HomeController/Index重定向?

  •  1
  • Roman Pokrovskij Archil Labadze  · 技术社区  · 7 年前

     public class HomeController : Controller
     {
            UserManager<WebUser> _userManager;
    
            public HomeController(UserManager<WebUser> _userManager)
            {
                this._userManager = _userManager;
            }
    
            [Authorize]
            public async Task<IActionResult> Index()
            {
                var user = await _userManager.GetUserAsync(User);
                if (user == null)
                {
                    return RedirectToPage("/Account/Login", new { area = "WebUserIdentity" });
                }
                return RedirectToPage("/Index", new { area = "Downloads" });
            }
     }
    

    此控制器/操作没有对应的视图。

    正因为如此,我陷入了困境:如何为razor页面配置路由以使用这些重定向(到两个不同的区域),而不创建“假”索引页面?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Roman Pokrovskij Archil Labadze    7 年前

    我相信您可以将控制器转换为创建索引页的页模型 Pages/IndexModel 做同样的重定向。

    public class IndexModel : PageModel {
        UserManager<WebUser> _userManager;
    
        public IndexModel(UserManager<WebUser> _userManager) {
            this._userManager = _userManager;
        }
    
        public async Task<IActionResult> OnGetAsync() {
            var user = await _userManager.GetUserAsync(User);
            if (user == null) {
                return RedirectToPage("/Account/Login", new { area = "WebUserIdentity" });
            }
            return RedirectToPage("/Index", new { area = "Downloads" });
        }
    }
    
        2
  •  1
  •   Edward    7 年前

    对于重定向到不同的页面,我建议您尝试 middleware

    app.Use(async (context, next) =>
            {
                // Do work that doesn't write to the Response.
                if (!context.User.Identity.IsAuthenticated && context.Request.Path != "/WebUserIdentity/Account/Login")
                {
                    context.Response.Redirect("/WebUserIdentity/Account/Login");
                }
                else if (context.Request.Path == "/")
                {
                    context.Response.Redirect("/Downloads/Index");
                }
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });
    
            app.UseMvc();