- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是“异步”和“任务”方面的新手。我似乎无法在 OnGetAsync() 中使用简单的 if{} else{}。
public async Task OnGetAsync()
{
if (HttpContext.Session.GetString("LoggedStatus") != null)
{
//KEEP GOING
Accounts = await _context.Accounts.ToListAsync();
}
else
{
RedirectToPage("./Index");
}
}
我收到的错误来自“帐户”页面,我试图通过使用“RedirectToPage(./Index”)”(我的主页)来避免接近该页面。我尝试在 RedirectToPage 前面放置“return”字样,但当我这样做时它变成红色。此外,如果满足第一个条件(Session 对象中有一个值),Accounts 页面将显示没有错误。所以,我很确定问题出在我尝试在“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)
上面的错误发生在 Accounts 中,它循环遍历并显示行。我不确定为什么它会到达 Accounts.chstml。
最佳答案
您需要使用 Task<IActionResult>
在public 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");
}
}
Microsoft 的文档在这里对此有一些很好的阅读:
根据评论,您可以运行此 w/o 异步。
public IActionResult OnGet()
{
if (HttpContext.Session.GetString("LoggedStatus") != null)
{
//KEEP GOING
Accounts = _context.Accounts.ToList();
return Page();
}
else
{
return RedirectToPage("./Index");
}
}
关于asp.net-core - 如果不满足条件,则从公共(public)异步任务 OnGetAsync() 重定向到不同的 Razor 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280282/
我开始学习 Razor Pages 的工作原理,教程提到 OnGet 和 OnPost,还提到我们也有异步选项:OnGetAsync 和 OnPostAsync。但是他们没有提到他们是如何工作的,显然
下面的代码返回一个 ArgumentNullException:值不能为 null。 (参数“来源”) 错误。该错误由 Model.Players.Any() 引发。页面似乎是在评估文件隐藏代码之前呈
我是“异步”和“任务”方面的新手。我似乎无法在 OnGetAsync() 中使用简单的 if{} else{}。 public async Task OnGetAsync() { if (Ht
我是“异步”和“任务”方面的新手。我似乎无法在 OnGetAsync() 中使用简单的 if{} else{}。 public async Task OnGetAsync() { if (Ht
我是一名优秀的程序员,十分优秀!