Search code examples
asp.net-coreasync-awaitrazor-pagesasp.net-core-2.2

If criteria not met redirect to different Razor Page from public async Task OnGetAsync()


I am new to the "async" and "task" stuff. I can't seem to get working a simple if{} else{} inside the OnGetAsync().

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

The error I get is from the Accounts page, which I am trying to avoid even going near by using the "RedirectToPage("./Index")" which is my Home page. I tried putting "return" word in front of RedirectToPage but it turns red when I do that. Also, if first condition is met (there is a value in the Session object) the Accounts pages shows up with no errors. So, I'm pretty sure the problem is in my attempt to redirect in the "else" statment.

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)

The error above is in Accounts right where it loops thru and displays rows. I'm not sure why it even gets to the Accounts.chstml.


Solution

  • You need to use Task<IActionResult> in public async Task<IActionResult> OnGetAsync(), combined with a return statement.

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

    Microsoft's docs has some good read on this here:


    Based on a comment, you can run this w/o async.

    public IActionResult OnGet()
    {
        if (HttpContext.Session.GetString("LoggedStatus") != null)
        {
            //KEEP GOING
            Accounts = _context.Accounts.ToList();
    
            return Page();
        }
        else
        {
            return RedirectToPage("./Index");
        } 
    }