如果不满足条件,则从公共异步任务 OnGetAsync() 重定向到不同的 Razor 页面

Jus*_*ohn 2 async-await asp.net-core razor-pages asp.net-core-2.2

我对“异步”和“任务”的东西很陌生。我似乎无法在 OnGetAsync() 内执行简单的 if{} else{} 操作。

public async Task OnGetAsync()
{
    if (HttpContext.Session.GetString("LoggedStatus") != null)
    {
        //KEEP GOING
    Accounts = await _context.Accounts.ToListAsync();
    }
    else
    {
    RedirectToPage("./Index");
    } 
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误来自帐户页面,我试图通过使用我的主页“RedirectToPage("./Index")”来避免接近该页面。我尝试将“返回”一词放在 RedirectToPage 前面,但当我这样做时它会变成红色。此外,如果满足第一个条件(会话对象中有一个值),则帐户页面将显示没有错误。所以,我很确定问题出在我尝试在“else”语句中重定向。

NullReferenceException: Object reference not set to an instance of an object.
OESAC.Pages.Accounts.Pages_Accounts_Index.ExecuteAsync() in Index.cshtml
+
        @foreach (var item in Model.Accounts)
Run Code Online (Sandbox Code Playgroud)

上面的错误出现在“帐户”中,它循环并显示行。我不知道为什么它会到达 Accounts.chstml。

LGS*_*Son 7

您需要将Task<IActionResult>inpublic async Task<IActionResult> OnGetAsync()return语句结合使用。

public async Task<IActionResult> OnGetAsync()
{
    if (HttpContext.Session.GetString("LoggedStatus") != null)
    {
        //KEEP GOING
        Accounts = await _context.Accounts.ToListAsync();

        return Page();
    }
    else
    {
        return RedirectToPage("./Index");
    } 
}
Run Code Online (Sandbox Code Playgroud)

微软的文档对此有一些很好的阅读:


根据评论,您可以运行此程序而无需异步。

public IActionResult OnGet()
{
    if (HttpContext.Session.GetString("LoggedStatus") != null)
    {
        //KEEP GOING
        Accounts = _context.Accounts.ToList();

        return Page();
    }
    else
    {
        return RedirectToPage("./Index");
    } 
}
Run Code Online (Sandbox Code Playgroud)