How to replace MVC HomeController/Index redirects

2019-06-08 03:12发布

问题:

I'm migrating from ASP MVC Classic to ASP Razor Pages.

Only one controller left to "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" });
        }
 }

There is no corresponded view to this controller/action.

And because of this I'm in stuck: how to configure routing for razor pages to use those redirects (to two different areas) without creating "fake" Index page?

回答1:

I believe you can convert the controller to create a Page model for index page Pages/IndexModel and do the same redirects.

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:

For redirecting to different pages, I suggest you try 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();