gpt4 book ai didi

c# - 出现一个或多个错误 : PostAsJsonAsync

转载 作者:太空狗 更新时间:2023-10-29 18:20:02 25 4
gpt4 key购买 nike

这是我得到的错误:

One or more errors occurred.
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at myProject.mymethod(Int32[] myIds) in path\MyClass.cs:line 758

这是方法:

private void mymethod(int[] myIds)
{
var uri = new Uri(string.Format(UriPath, string.Format(MyPath)));
var client = GetHttpClient(uri);

var postModel = new PostModel
{
Ids = myIds,
LastUpdate = NewItem ? null : _lastUpdated
};

if (client != null)
{
var response = client.PostAsJsonAsync(uri, postModel).Result;//this line crashes

if (response.IsSuccessStatusCode)
{
//doSomething
}
}
}

我调用了很多这样的方法,除了这个之外,所有方法都有效。当它被击中时,它会花费很多时间然后抛出这个异常。使用所有其他方法都不会发生错误。

这是内部异常:

Inner.System.Threading.Tasks.TaskCanceledException: A task was canceled.

这是我的 GetCLient() 方法:

private HttpClient GetHttpClient(Uri uri)
{
var handler = new HttpClientHandler
{
CookieContainer = CoockieContainer
};

return new HttpClient(handler)
{
BaseAddress = uri
};
}

这是 API 方法:

[HttpPost]
public IList<MyModel> MyAPIMethod(PostModel model)
{
List<MyModel> myTranslations;
using (var db = new myEntities(GetDbConnStrByUser(new GetCookies().GetUserName())))
{
myTranslations = db.tblTranslations.Where(it => model.Ids.Contains(it.id)
&& (!model.Update.HasValue || it.update > model.LastUpdate.Value))
.Select(it => new MyModel
{
Id = it.id,
Name = it.name,
Description = it.desc,
LanguageId = it.language_id
}).ToList();
}

return myTranslations.GroupBy(x => new { x.Id, x.LanguageId }).Select(x => x.First()).ToList();
}

可能发生超时。

Fiddler 返回此错误:WAITING操作超时。

最佳答案

.Result 尝试将 Task 变成 T。它同步阻塞等待任务完成,只有在没有异常发生时才会返回 T。您应该预料到的两种类型的异常是 OperationCanceledExceptions/TaskCanceledExceptions(当 HTTP 请求超时或使用 CancellationToken 并且 token 被取消时——我认为后者在这里不适用)和一般/HTTP 相关的异常。

您可能遇到了 HTTP 超时情况。抛出异常需要很长时间吗?如果不是,您的 GetHttpClient 方法是什么样的?是否明确设置超时或取消标记?

如果你想坚持使用同步方法而不返回任务,你应该做这样的事情:

try
{
var response = client.PostAsJsonAsync(uri, postModel).Result;//this line crashes
}
catch (OperationCanceledException oce)
{
// Tell the user that the request timed our or you cancelled a CancellationToken
}
catch (Exception exc)
{
// Look at the HttpClient docs and try to catch something more specific. You don't want
// to swallow StackOverflowExceptions or OutOfMemoryExceptions.
}

如果您愿意尝试异步,这就是您要寻找的:

private async Task mymethodAsync(int[] myIds)
{
var uri = new Uri(string.Format(UriPath, string.Format(MyPath)));
var client = GetHttpClient(uri);

var postModel = new PostModel { ... };

if (client != null)
{
try
{
var response = await client.PostAsJsonAsync(uri, postModel);

if (response.IsSuccessStatusCode)
{
//doSomething
}
}
catch (OperationCanceledException oce)
{
// because timeouts are still possible
}
catch (Exception exc) {
// Because other things can still go wrong too (HTTP 500, parsing errors)
}
}
}

有关 .Result 调用如何使用 HttpClient 工作的更多信息,请参见此处:What happens while waiting on a Task's Result?

关于c# - 出现一个或多个错误 : PostAsJsonAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26343940/

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