【发布时间】:2022-02-17 02:53:43
【问题描述】:
我从 API 获取大量数据的代码是这样的
public static async Task<model> GetDataAsyncs(string url)
{
// Initialization.
mymodel responseObj = new mymodel();
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
using (var client = new HttpClient(httpClientHandler))
{
// Setting Base address.
client.BaseAddress = new Uri(apiBasicUri);
// Setting content type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Initialization.
HttpResponseMessage response = new HttpResponseMessage();
// HTTP Get
response = await client.GetAsync(url ).ConfigureAwait(false);
// Verification
if (response.IsSuccessStatusCode)
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
responseObj.Status = true;
responseObj.Data = result;
}
}
}
return responseObj;
}
我在我的控制器中调用上面的函数
public ActionResult myActionMethod()
{
string res= helper.GetDataAsync("url").Result.Data;
}
有时这会引发错误 system.threading.tasks.taskcanceledexception a task was canceled 。这不会每次都发生。谁能指出我在这里做错了什么?
【问题讨论】:
-
当客户端(浏览器)取消请求时(例如在浏览器中点击“停止”按钮),服务器将通过抛出
TaskCanceledException来停止处理请求。这可能是正在发生的事情吗? -
@GabrielLuci 不,页面开始加载后没有用户操作
标签: c# asp.net-mvc async-await