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

How to replace MVC HomeController/Index redirects with RazorPages routings?

我正在从 ASP MVC Classic 迁移到 ASP Razor Pages。

只剩下一个控制器给"migrate":HomeController

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

没有对应的视图controller/action。

因此我陷入困境:如何为剃刀页面配置路由以使用这些重定向(到两个不同的区域)而不创建 "fake" 索引页面?

我相信您可以转换控制器以创建索引页面的页面模型 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" });
    }
}

为了重定向到不同的页面,我建议您尝试 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();