简体   繁体   English

PostAsync方法的HttpClient错误

[英]HttpClient error with PostAsync method

When making PostAsync call using HttpClient to a 3rd party API. 使用HttpClient对第三方API进行PostAsync调用时。 I am seeing this error exactly when I do client.PostAsync. 当我做client.PostAsync时,我正好看到这个错误。 Any idea what could have been causing this? 知道是什么导致了这个吗?

Code: 码:

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 };
    }
}

Error: 错误:

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()

Add these two lines to your web.config file: 将这两行添加到web.config文件中:

// First tag might exist already
<httpRuntime targetFramework="4.5" />
<appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

Im quoting this link : 我引用此链接

Enables the new await-friendly asynchronous pipeline that was introduced in 4.5. 启用4.5中引入的新的等待友好的异步管道。 Many of our synchronization primitives in earlier versions of ASP.NET had bad behaviors, such as taking locks on public objects or violating API contracts. 早期版本的ASP.NET中的许多同步原语都有不良行为,例如对公共对象进行锁定或违反API协定。 In fact, ASP.NET 4's implementation of SynchronizationContext.Post is a blocking synchronous call! 实际上,ASP.NET 4的SynchronizationContext.Post实现是一个阻塞同步调用! The new asynchronous pipeline strives to be more efficient while also following the expected contracts for its APIs. 新的异步管道努力提高效率,同时遵循API的预期合同。 The new pipeline also performs a small amount of error checking on behalf of the developer, such as detecting unanticipated calls to async void methods. 新管道还代表开发人员执行少量错误检查,例如检测对异步void方法的意外调用。

Certain features like WebSockets require that this switch be set. WebSockets等某些功能需要设置此开关。 Importantly, the behavior of async / await is undefined in ASP.NET unless this switch has been set. 重要的是,除非已设置此开关,否则在ASP.NET中未定义async / await的行为。 (Remember: setting is also sufficient.) (记住:设置也足够了。)

I would change 我会改变

var response = client.PostAsync(ServiceUrl, formData).Result

to

var response = await client.PostAsync(ServiceUrl, formData);

And then monitor for errors after that. 然后监视错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpClient PostAsync方法引发聚合异常 - HttpClient PostAsync method throw Aggregate Exception 在 C# 中使用带有 API 密钥的 HttpClient 类中的 PostAsync 方法 - Using PostAsync method from HttpClient Class with an API key in C# 即使使用ConfigureAwait(false),HttpClient的PostAsync方法也会阻塞 - HttpClient's PostAsync method blocks even though ConfigureAwait(false) is used HttpClient.PostAsync() 方法在 C# xUnt 测试中永远挂起 - HttpClient.PostAsync() method is hanging forever in C# xUnt test HttpClient 的 PostAsync 方法在 2-3 个超时请求后抛出聚合异常 - PostAsync method of HttpClient throws an Aggregate exception after 2-3 timeout requests httpClient.PostAsync返回“不允许使用方法”(在winform应用程序中运行) - httpClient.PostAsync returns “Method Not Allowed” (running in winform app) 如何通过 HttpClient PostAsync 方法将文件和参数上传到远程服务器? - How to upload a file and a parameter to a remote server via HttpClient PostAsync method? 如何在调用HttpClient PostAsync方法上传图像时解决HttpRequestException - How to solve HttpRequestException while calling HttpClient PostAsync method to upload image WPF 应用程序在 HttpClient PostAsync 方法中无响应或异常退出 - WPF App exits without response or exception at HttpClient PostAsync method C# HttpClient.PostAsync 不返回或抛出错误 - C# HttpClient.PostAsync doesn't return or throw an error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM