0

我正在玩 Silverlight 4,当我的页面加载时,我打电话

beginGet("my/people/", new OpenReadCompletedEventHandler(continueLoadStamData));

我定义为

private void beginGet(string endpoint, OpenReadCompletedEventHandler callback)
{
  WebClient wc = new WebClient();
  wc.Credentials = new NetworkCredential(username, password);
  wc.OpenReadCompleted += callback;
  wc.OpenReadAsync(new Uri(baseURL + endpoint));
}

和 continueLoadStamData()

void continueLoadStamData(object sender, OpenReadCompletedEventArgs e)
{
  JsonObject root = (JsonObject)JsonObject.Load(e.Result);
}

我的问题是,当我到达 e.Result 时,它会引发异常。这与我尝试使用时遇到的异常相同WebRequest req = ...; req.Credentials = new NetworkCredential(username, password)

{System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details. ---> System.Net.WebException: An exception occurred during a WebClient request. ---> System.NotImplementedException: This property is not implemented by this class.
   at System.Net.WebRequest.set_Credentials(ICredentials value)
   at System.Net.WebClient.GetWebRequest(Uri address)
   at System.Net.WebClient.OpenReadAsync(Uri address, Object userToken)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at System.Net.OpenReadCompletedEventArgs.get_Result()
   at JSONSample.MainPage.continueLoadStamData(Object sender, OpenReadCompletedEventArgs e)
   at System.Net.WebClient.OnOpenReadCompleted(OpenReadCompletedEventArgs e)
   at System.Net.WebClient.OpenReadOperationCompleted(Object arg)}

您对发生的事情有任何想法吗,我如何确保实施基本身份验证并让我的请求继续进行?

干杯

尼克

4

1 回答 1

1

根据Mark Monster 在此处的帖子,您的 beginGet 方法中缺少一些代码行。它应该是这样的:

private void beginGet(string endpoint, OpenReadCompletedEventHandler callback)
{
  WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);  
  WebClient wc = new WebClient();  
  wc.Credentials = new NetworkCredential(username, password);
  wc.UseDefaultCredentials = false; 
  wc.OpenReadCompleted += callback;  
  wc.OpenReadAsync(new Uri(baseURL + endpoint));
}

此外,如果您只是想从服务器获取 JSON,您应该能够使用 DownloadStringAsync 而不是 OpenReadAsync,这可能会简化事情。

于 2009-12-02T23:48:22.310 回答