【问题标题】:Why does this MVC async action fail?为什么这个 MVC 异步操作会失败?
【发布时间】:2014-05-15 22:50:16
【问题描述】:

我正在尝试使用异步控制器操作,以遵循典型 Identity 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());
}

其中 Context 是典型的 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;
}

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

【问题讨论】:

    标签: c# asp.net-mvc razor async-await


    【解决方案1】:

    您的CurrentCandidateId 函数是async 并返回Task&lt;int&gt;DbSet.FindAsync 接受任何类型的对象,但它肯定不知道如何处理 Task&lt;int&gt;。相反,您需要在该任务上 await 并将其结果传递给 FindAsync

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

    【讨论】:

    • 刚刚在您回答的同时发现缺少await。做得好。 :) 我猜那是因为FindAsyncobject[] 作为参数,所以编译器没有警告:)
    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多