[英]HttpClient error with PostAsync method
使用HttpClient对第三方API进行PostAsync调用时。 当我做client.PostAsync时,我正好看到这个错误。 知道是什么导致了这个吗?
码:
public class JobController : AsyncController
{
public ActionResult ViewPage()
{
return View("~/Views/Pages/Submit.cshtml");
}
private const string ServiceUrl = "https://api.3points.io/v1/applications/";
[HttpPost]
public async Task<ActionResult> Submit()
{
var client = new HttpClient();
var formData = new MultipartFormDataContent();
var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("abc123"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
foreach (var key in Request.Form.AllKeys)
formData.Add(new StringContent(Request.Form[key]), String.Format("\"{0}\"", key));
foreach (string key in Request.Files.AllKeys)
{
var file = Request.Files[key];
if (file == null || file.ContentLength <= 0) continue;
HttpContent fileStream = new StreamContent(file.InputStream);
formData.Add(fileStream, key, file.FileName);
}
var response = await client.PostAsync(ServiceUrl, formData);
var success = "True";
if (!response.IsSuccessStatusCode) success = "False";
return new JsonResult { Data = success };
}
}
错误:
System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=System.Web
StackTrace:
at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state)
at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state)
at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.AwaitTaskContinuation.<ThrowAsyncIfNecessary>b__1(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
将这两行添加到web.config文件中:
// First tag might exist already
<httpRuntime targetFramework="4.5" />
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
我引用此链接 :
启用4.5中引入的新的等待友好的异步管道。 早期版本的ASP.NET中的许多同步原语都有不良行为,例如对公共对象进行锁定或违反API协定。 实际上,ASP.NET 4的SynchronizationContext.Post实现是一个阻塞同步调用! 新的异步管道努力提高效率,同时遵循API的预期合同。 新管道还代表开发人员执行少量错误检查,例如检测对异步void方法的意外调用。
WebSockets等某些功能需要设置此开关。 重要的是,除非已设置此开关,否则在ASP.NET中未定义async / await的行为。 (记住:设置也足够了。)
我会改变
var response = client.PostAsync(ServiceUrl, formData).Result
至
var response = await client.PostAsync(ServiceUrl, formData);
然后监视错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.