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

。_饼干妹妹 提交于 2019-12-13 19:04:50

问题


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();


来源:https://stackoverflow.com/questions/52711158/how-to-replace-mvc-homecontroller-index-redirects-with-razorpages-routings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!