gpt4 book ai didi

c# - REST API 代码片段在 ASP.NET 网页中抛出 NullReferenceException,但在 WinForms 中运行良好

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:17 25 4
gpt4 key购买 nike

在 WinForms 中使用以下代码片段,我能够通过 REST API 成功上传文档。但是,一旦我转到 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;
}
}
}

我已经调试了clienturlByteArrayContent,它们都不为空。但我仍然遇到未处理的异常。

以下是异常的详细信息:

   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.Web.LegacyAspNetSynchronizationContext.Post(SendOrPostCallback callback, Object state)
at System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction(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.<>c.<ThrowAsyncIfNecessary>b__18_0(Object s)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
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()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

最佳答案

堆栈跟踪中存在“LegacyAspNetSynchronizationContext”是错误的线索。

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

<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>

来自documentation (强调):

Setting this compatibility switch is mandatory for WebSockets-enabled applications, for using Task-based asynchrony in Web Forms pages, and for certain other asynchronous behaviors.

更新:如果您想从非异步方法调用异步方法,并且您不关心结果,那么一种方法是使用 Task.Run:

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

关于c# - REST API 代码片段在 ASP.NET 网页中抛出 NullReferenceException,但在 WinForms 中运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871240/

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