简体   繁体   中英

ASP.NET Core 2.2 Razor Pages why does OnPost() work, but OnPostAsync() doesn't?

Please would someone explain why OnPost() works, but OnPostAsync() doesn't. Another post said there wasn't a difference, but seemingly there is...

This works

public async Task<IActionResult> OnPost()
{
   LoggedInUser = await _userManager.GetUserAsync(User);
   if (LoggedInUser == null)
      SetPageStatusMsg("No user logged in");
   else
      SetPageStatusMsg($"{LoggedInUser.UserName} is logged-in");

   return Page();
}

but this doesn't even get called

public async Task<IActionResult> OnPostAsync()
{
   LoggedInUser = await _userManager.GetUserAsync(User);
   if (LoggedInUser == null)
      SetPageStatusMsg("No user logged in");
   else
      SetPageStatusMsg($"{LoggedInUser.UserName} is logged-in");

   return Page();
}

Perhaps it's a Core 2.2 thing, but there's no error as we never make mistakes in Core 2.2 ;-)

I would recommend upgrading ASP.NET Core 2.2 to Core 3.0., and rebuilding the project. It should help.

At the same time, please make sure that normal handler and Async handler are not used at the same time, below some more information on that.

As this source stated: https://www.learnrazorpages.com/razor-pages/handler-methods

"OnGet and OnGetAsync are the same handler. Cannot have both in the same page. If you do, the framework will raise an exception:

InvalidOperationException: Multiple handlers matched. The following handlers matched route data and had all constraints satisfied:

Void OnGetAsync(), Void OnGet() "

From my experience, I tried using OnPostAsync and OnPost handler at the same time, and I got the following error:

An unhandled exception occurred while processing the request. InvalidOperationException: Multiple handlers matched. The following handlers matched route data and had all constraints satisfied: Microsoft.AspNetCore.Mvc.IActionResult OnPost(),System.Threading.Task'1[Microsoft.AspNetCore.Mvc.IActionResult] OnPostAsync()

So, to solve this issue you could use either use one OnPostAsync or one OnPost. That is my idea, please tell me if you have something more to it. Here is more information: https://codingblast.com/asp-net-core-razor-pages-handlers/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM