C# REST API代码段在WinForms中正常运行时在ASP.NET网页中引发NullReferenceException

C# REST API代码段在WinForms中正常运行时在ASP.NET网页中引发NullReferenceException,c#,asp.net,async-await,nullreferenceexception,C#,Asp.net,Async Await,Nullreferenceexception,在WinForms中使用以下代码片段,我成功地通过RESTAPI上传了文档。但一旦我转到ASP.NET,它就会抛出一个NullReferenceException public async Task<string> TestUpload() { const string cServerBaseAddress = "https://test-testrestservice.abcd.com/"; const string cFilename =

在WinForms中使用以下代码片段,我成功地通过RESTAPI上传了文档。但一旦我转到ASP.NET,它就会抛出一个NullReferenceException

public async Task<string> TestUpload()
    {
        const string cServerBaseAddress = "https://test-testrestservice.abcd.com/";
        const string cFilename = @"D:\temp\Test.txt";
        const string cUrl = "{0}abc/dms/api/v1/crmdocuments/?BusinessUnit={1}&AccountID={2}&DocumentType={3}&Description={4}&Filename={5}";
        string businessUnit = "XYZ";
        string accountID = "ABCCompany";
        string docType = "Affidavit";
        string description = @"\%&description&%/";
        string responseContent = string.Empty;
        try
        {
            string url = string.Format(cUrl, cServerBaseAddress,
            WebUtility.UrlEncode(businessUnit), WebUtility.UrlEncode(accountID),
            WebUtility.UrlEncode(docType), WebUtility.UrlEncode(description),
            WebUtility.UrlEncode(Path.GetFileName(cFilename)));
            using (HttpClient client = GetClient(cServerBaseAddress))
            {
                using (HttpResponseMessage response = await client.PostAsync(url, new ByteArrayContent(File.ReadAllBytes(cFilename))))
                {
                    responseContent = await response.Content.ReadAsStringAsync();
                    response.EnsureSuccessStatusCode();
                    string newContentId = Newtonsoft.Json.Linq.JToken.Parse(response.Content.ReadAsStringAsync().Result).ToString();
                    return newContentId;
                }
            }
        }
堆栈跟踪中出现的“LegacyAspNetSynchronizationContext”是一条错误线索

如果要在ASP.NET 4.5中使用
wait
,则必须在Web.config中添加以下元素:

(重点添加):

对于启用WebSocket的应用程序,对于在Web表单页面中使用基于任务的异步,以及对于某些其他异步行为,必须设置此兼容性开关

更新:如果要从非异步方法调用异步方法,并且不关心结果,则一种方法是使用Task。运行:

Task.Run(() => TestUpload());

空异常具体是什么?可能是您缺少
url
和/或配置设置。我检查了它们是否都为null或空。我还用stack Trace更新了这个问题一些可能无法解决特定问题的要点:a)在尝试阅读内容之前调用
ensureccessstatuscode()
;b) 在此代码中没有声明
responseContent
,那么它在哪里声明?;c) 这可能只是一个调整后的代码片段,但通常不要为每个请求创建和处理
HttpClient
——创建一个实例,并按预期将其用于整个应用程序;d) 将
response.Content.ReadAsStringAsync().Result
更改为
responseContent
@sellotape这是整个程序通过api上传文档的一部分。如果您希望我在这里更新为well@J.Doe-我认为没有人想要(或会在一个SO问题中阅读)1500行代码:)您是否尝试过Michael Liu的答案,以及先运行
ensureAccess StatusCode()
?可能是你收到了非2xx的回复。谢谢Mich,我把那个片段添加到了。现在,我没有遇到异常,但断点没有返回到最后一段代码。请编辑您的帖子,并展示如何调用此代码段。您可能会遇到死锁(如果您正在访问任务的Result属性,则可能会发生死锁)。此函数放在一个函数中,并且一次调用整个函数。我也更新了代码,单击按钮调用它,TestUpload();您是在等待结果,还是正在访问任务的result属性?
Task.Run(() => TestUpload());