如何使用Web api2在asp.net MVC中创建异步和等待方法

时间:2016-05-04 07:00:24

标签: c# async-await asp.net-web-api2 c#-5.0 asp.net-mvc-5.1


    我刚接触使用Web API 2的ASP.NET MVC,我使用带有Web API 2的asp.net MVC创建了async和await方法,它将存储到SQL DB中。当我尝试在API控制器中调用我的存储库方法时,我得到一个错误,无法等待“system.collections.generic.list”。如果有人知道它,请告诉我。
注意: - 我不想使用实体框架,而是想通过存储过程存储数据。

Model:

namespace AsyncMVCWEBAPI.Models
{
    public class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string Category { get; set; }
    }
}

API Controller:

public static async Task<Product> GetProduct()
{
    return await GetAllProduct(); // Here i'm getting an error can not await "system.collections.generic.list"
}

Repository:

public static IEnumerable<Product> GetAllProduct()
{           
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        List<Product> students = new List<Product>();
        SqlCommand cmd = new SqlCommand("spGetAllStudentDetails", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())
        {
            Product product = new Product();
            product.Price = Convert.ToInt32(rdr["Price"]);
            product.Name = rdr["Name"].ToString();
            product.Category = rdr["Category"].ToString();

            students.Add(product);

        }
        return students;
    }           
}

enter image description here

2 个答案:

答案 0 :(得分:3)

主要问题是您无法等待非异步的方法。您应该重写GetAllProduct方法,使其与以下签名异步:

public static async Task<IEnumerable<Product>> GetAllProduct()

另外,不要忘记使用Async方法从数据库中获取数据:

    ...
    await con.OpenAsync();
    ...
    SqlDataReader rdr = await cmd.ExecuteReaderAsync();
    while (await rdr.ReadAsync())
    {
        ...
        students.Add(product);
    }
    return students;

答案 1 :(得分:0)

正如之前的回答所说,您必须将签名更改为:

public static async Task<IEnumerable<Product>> GetAllProduct()

如果您想跳过ADO.NET样板内容,可以使用Dapperhttps://github.com/StackExchange/dapper-dot-net)来简化代码:

public static async Task<IEnumerable<Product>> GetAllProduct()
{
    using (var con = new SqlConnection(connectionString))
    {
        await con.OpenAsync();
        return await con.QueryAsync<Product>("spGetAllStudentDetails", commandType: CommandType.StoredProcedure);
    }
}