gpt4 book ai didi

c# - 如何使用 Web api2 在 asp.net MVC 中制作异步和等待方法

转载 作者:太空宇宙 更新时间:2023-11-03 23:16:40 25 4
gpt4 key购买 nike


我刚接触带有 Web API 2 的 ASP.NET MVC,我通过使用带有 Web API 2 的 asp.net MVC 创建了异步和等待方法,该方法将存储到 SQL DB 中。当我尝试在 API Controller 中调用我的存储库方法时,出现错误无法等待“system.collections.generic.list”。如果有人对此有任何想法,请告诉我。
注意:- 我不想使用 Entity Framework ,而是想通过存储过程存储数据。

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

最佳答案

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

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

也不要忘记使用异步方法从数据库中获取数据:

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

关于c# - 如何使用 Web api2 在 asp.net MVC 中制作异步和等待方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37020615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com