与PostAsync方法HttpClient的错误 [英] HttpClient error with PostAsync method

查看:4242
本文介绍了与PostAsync方法HttpClient的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使得使用HttpClient的一个第三方API PostAsync电话时。当我做client.PostAsync我正是看到了这个错误。任何想法可能已经造成的?

code:

 公共类JobController:AsyncController
{
    公众的ActionResult的ViewPage()
    {
        返回视图(〜/查看/页/ Submit.cshtml);
    }    私人常量字符串的serviceUrl =htt​​ps://api.3points.io/v1/applications/;    [HttpPost]
    公共异步任务<&的ActionResult GT;提交()
    {
        VAR的客户=新的HttpClient();
        VAR FORMDATA =新MultipartFormDataContent();
        变种EN codeD = Convert.ToBase64String(Encoding.UTF8.GetBytes(ABC123));
        client.DefaultRequestHeaders.Authorization =新AuthenticationHeaderValue(基本,恩codeD);        的foreach(在Request.Form.AllKeys VAR键)
            formData.Add(新的StringContent(的Request.Form [关键])的String.Format(\\{0} \\,键));        的foreach(在Request.Files.AllKeys字符串键)
        {
            var文件= Request.Files [关键]
            如果(文件== NULL || file.ContentLength< = 0)继续;            HttpContent FILESTREAM =新StreamContent(file.InputStream);
            formData.Add(FILESTREAM,钥匙,file.FileName);
        }        VAR响应=等待client.PostAsync(serviceURL中,FORMDATA);        VAR成功=真;
        如果(response.IsSuccessStatus code!)成功=FALSE;        返回新JsonResult {数据=成功};
    }
}

错误:

  System.NullReferenceException了未处理
的HResult = -2147467261
消息=对象引用未设置到对象的实例。
来源=的System.Web
堆栈跟踪:
   在System.Web.ThreadContext.AssociateWithCurrentThread(布尔setImpersonationContext)
   在System.Web.HttpApplication.OnThreadEnterPrivate(布尔setImpersonationContext)
   在System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback回调,对象状态)
   在System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback回调,对象状态)
   在System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback回调,对象状态,任务和放大器; currentTask)
---从previous位置堆栈跟踪,其中引发异常的结尾---
   在System.Threading.Tasks.AwaitTaskContinuation< ThrowAsyncIfNecessary> b__1(一个Object)
   在System.Threading.ExecutionContext.RunInternal(ExecutionContext中的ExecutionContext,ContextCallback回调,对象状态,布尔preserveSyncCtx)
   在System.Threading.ExecutionContext.Run(ExecutionContext中的ExecutionContext,ContextCallback回调,对象状态,布尔preserveSyncCtx)
   在System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   在System.Threading.ThreadPoolWorkQueue.Dispatch()


解决方案

我会改变

  VAR响应= client.PostAsync(serviceURL中,FORMDATA)。结果

  VAR响应=等待client.PostAsync(serviceURL中,FORMDATA);

和然后监视后的错误。

When making PostAsync call using HttpClient to a 3rd party API. I am seeing this error exactly when I do 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()

解决方案

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.

这篇关于与PostAsync方法HttpClient的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆