如何返回ASP.NET Web API异步控制器方法中的对象列表或将列表包装在Task对象中?
类别:
public class SubscriberHistory
{
public string Date;
public string Message;
public SubscriberHistory(string Date, string Message)
{
this.Date = Date;
this.Message = Message;
}
}
控制器:
[HttpGet("[action]/{accountNumber}")]
public Task<SubscriberHistory> GetSubscriberHistory(string accountNumber)
{
SubscriberManager subsManager = new SubscriberManager();
return subsManager.GetSubscriberHistoryByAccountNumber(accountNumber);
}
控制器管理员:
public async List<SubscriberHistory> GetSubscriberHistory()
{
List<SubscriberHistory> List = new List<SubscriberHistory>();
// HttpClient get data
return List; // ?
}
答案 0 :(得分:3)
如果您没有执行任何操作Task
,切勿从操作方法返回async
:它没用,也会给您的通话增加不必要的开销。
要返回对象列表,只需声明正确的返回类型:
[HttpGet("[action]/{accountNumber}")]
public List<SubscriberHistory> GetSubscriberHistory(string accountNumber)
{
SubscriberManager subsManager = new SubscriberManager();
return subsManager.GetSubscriberHistoryByAccountNumber(accountNumber);
}
如果您想要异步执行,那么您必须返回Task<T>
并等待结果:
[HttpGet("[action]/{accountNumber}")]
public async Task<List<SubscriberHistory>> GetSubscriberHistory(string accountNumber)
{
SubscriberManager subsManager = new SubscriberManager();
return await subsManager.GetSubscriberHistoryByAccountNumber(accountNumber);
}
在你的经理中:
public async Task<List<SubscriberHistory>> GetSubscriberHistory()
{
List<SubscriberHistory> list = new List<SubscriberHistory>();
var result = await client.GetAsync("http://myhost/mypath");
//Your code here
return list;
}
答案 1 :(得分:1)
如果要使用Async Controller,则需要更新代码:
[HttpGet("[action]/{accountNumber}")]
public async Task<IHttpActionResult> GetSubscriberHistory(string accountNumber)
{
SubscriberManager subsManager = new SubscriberManager();
return await subsManager.GetSubscriberHistoryByAccountNumber(accountNumber);
}
如果要使用异步控制器,则应在控制器功能中存在异步和等待。 谢谢!