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

时间:2018-10-08 23:04:20

标签: asp.net-core asp.net-core-mvc asp.net-core-2.1 razor-pages

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

仅剩一个控制器可以“迁移”: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" });
        }
 }

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

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

2 个答案:

答案 0 :(得分:1)

我相信您可以将控制器转换为索引页面Pages/IndexModel创建一个Page模型,并执行相同的重定向。

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

答案 1 :(得分:1)

要重定向到其他页面,建议您尝试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();