【问题标题】:Web Client - Asynchronous operations are not allowed in this contextWeb 客户端 - 在此上下文中不允许异步操作
【发布时间】:2012-05-18 07:38:19
【问题描述】:

它是一个类库,它被从网页中调用

try
  {
    System.Net.WebClient wc = WebAccess.GetWebClient();
    wc.UploadStringCompleted += new System.Net.UploadStringCompletedEventHandler(wc_UploadStringCompleted);
    wc.UploadStringAsync(new Uri("http://" + MobileWLCUrl + urlCreateCacheAPI), GetJSONforGetMenuDetails(Id, MenuIds));                    
  }
catch (Exception ex) { EngineException.HandleException(ex); }

void wc_UploadStringCompleted(object sender, System.Net.UploadStringCompletedEventArgs e)
    {
        string result = e.Result;
        EngineException.CreateLog("Cache Created (for Menus: " + MenuIds + ") in API for LocationId: " + LocId);
    }

大家好,我试图异步访问这个 url,它给了我这个错误,任何帮助都会得到帮助。

Asynchronous operations are not allowed in this context. 
Page starting an asynchronous operation has to have the Async attribute set to true 
and an asynchronous operation can only be started on a page prior to PreRenderComplete event. 

at System.Web.AspNetSynchronizationContext.OperationStarted()
at System.Net.WebClient.UploadStringAsync(Uri address, String method, String data, Object userToken)
at System.Net.WebClient.UploadStringAsync(Uri address, String data)

谢谢...

【问题讨论】:

  • 这个没有答案??我认为这是我面临的一个常见错误,真的很失望

标签: c# .net asynchronous webclient class-library


【解决方案1】:

Async="true" 参数添加到@Page 指令。

<%@ Page Async="true" ... %>

西瓦尼,

您需要在以下代码调用的页面(存储在"http://" + MobileWLCUrl + urlCreateCacheAPI)中应用此更改:

wc.UploadStringAsync(new Uri("http://" + MobileWLCUrl + urlCreateCacheAPI), GetJSONforGetMenuDetails(Id, MenuIds)); 

【讨论】:

  • 你的意思是页面m调用它?这是一个 .cs 文件,我从代码后面的页面调用这个类,我添加了这个,但结果仍然很好,它一直给我这个异常
  • 页面指令可在 aspx 页面上找到。
  • 我将它添加到页面中,但仍然没有成功
  • Sirwani,我想你已经修改了调用页面上的页面指令。在“UploadStringAsync”函数中更新被调用页面上的指令。
  • 它是一个类库而不是一个 aspx 页面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 2012-11-17
相关资源
最近更新 更多