开发者

Possible authentication problem? Loading a JSON via WebClient in Silverlight 4

I'm playing with Silverlight 4, and I when my page loads, I call

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

that I have defined as

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));
}

and continueLoadStamData()

void continueLoadStamData(object sender, OpenReadCompletedEventArgs e)
{
  JsonObject root = (JsonObject)JsonObject.Load(e.Result);开发者_如何学运维
}

My problem is that when I get to e.Result, it throws an exception. It is the same exception I get as when I tried to use 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)}

Do you have any idea of what's going on, how I can make sure basic authentication is implemented and get my request going?

Cheers

Nik


Based on Mark Monster's post here you're missing some lines of code in your beginGet method. It should be something like:

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));
}

Also, if you're just trying to get JSON from the server, you should be able to use DownloadStringAsync instead of OpenReadAsync which might simplify things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜