为什么此 MVC 异步操作失败

本文关键字:失败 异步操作 MVC 为什么 | 更新日期: 2023-09-27 17:56:43

我正在尝试使用异步控制器操作来遵循典型身份AccountController代码的模式,但是如果我直接访问该页面,则会出现以下错误(如果我在登录后通过重定向,则静默挂起):

The specified parameter type 'System.Threading.Tasks.Task`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.
Parameter name: item 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
 Exception Details: System.ArgumentOutOfRangeException: The specified parameter type 'System.Threading.Tasks.Task`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.
Parameter name: item
Source Error: 
Line 107:        public async Task<Candidate> CurrentCandidate()
Line 108:        {
Line 109:            return await this.Context.Candidate.FindAsync(this.CurrentCandidateId());
Line 110:        }
Line 111:

控制器操作(尚未对用户执行任何操作):

public async Task<ActionResult> Index(int id = 0)
{
    // Get current user
    var candidate = await base.CurrentCandidate();
    if (candidate != null)
    {
        ApplicationUser user = await UserManager.FindByIdAsync(candidate.CandidateGuid.ToString());
    }
    return View();
}

它调用的基本帮助程序方法是:

/// <summary>
/// Return the current logged-in candidate, based on the current candidate id
/// </summary>
public async Task<Candidate> CurrentCandidate()
{
    return await this.Context.Candidate.FindAsync(this.CurrentCandidateId());
}

其中上下文是典型的 EF6 数据库上下文。

涉及的最后一个帮助程序方法是:

public async Task<int> CurrentCandidateId()
{
    if (User.Identity.IsAuthenticated)
    {
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user != null)
        {
            return user.CandidateId.GetValueOrDefault(0);
        }
    }
    return 0;
}

我忽略了什么?我是这种新风格的异步编码的新手,所以请随时教育我:)

为什么此 MVC 异步操作失败

您的CurrentCandidateId函数async并返回一个Task<int>DbSet.FindAsync接受任何类型的物体,但它绝对不知道如何处理Task<int>。相反,您需要await该任务并将其结果传递给FindAsync

public async Task<Candidate> CurrentCandidate()
{
    return await this.Context.Candidate
        .FindAsync(await this.CurrentCandidateId());
    //             ^^^^^
}