0

我正在尝试向 Web 服务发出一个简单的请求。代码在后台执行,而不是 UI 线程。Uri 包含正确的地址,该地址始终返回带有 200 HTTP 代码的结果。一切都在模拟器上进行。

var request = WebRequest.Create(uri);
try
{
    var ar = request.BeginGetResponse(_ => { }, null);
    using (var response = request.EndGetResponse(ar)) //NullReferenceException rises here
    using (var stream = response.GetResponseStream())
    {
        var serializer = new DataContractJsonSerializer(typeof(AuthResult));
        return (AuthResult)serializer.ReadObject(stream);
    }
}
catch (Exception e)
{
    return new AuthResult { Error = e.Message };
}

没有调试器代码总是失败。附加调试器时,它很少失败。

System.NullReferenceException occurred
  Message=NullReferenceException
  StackTrace:
   at System.Net.Browser.ClientHttpWebRequest.InvokeGetResponseCallback(Object state)
   at System.Net.Browser.ClientHttpWebRequest.Completed(Object sender, EventArgs e)
   at MS.Internal.InternalWebRequest.OnCompleted(Object sender, EventArgs args)
   at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)

下一个:

System.Net.WebException occurred
Message=The remote server returned an error: NotFound.
StackTrace:
   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at Contest.InteropApi.SignIn(Uri uri)
   at Contest.ViewModel.LoginViewModel.<PerformSignIn>b__4()
   at System.Reactive.Linq.QueryLanguage.<>c__DisplayClass3b`1.<>c__DisplayClass3d.<ToAsync>b__3a()
   at System.Reactive.Concurrency.Scheduler.Invoke(IScheduler scheduler, Action action)
   at System.Reactive.Concurrency.DefaultScheduler.<>c__DisplayClass1`1.<Schedule>b__0(Object _)
   at System.Reactive.Concurrency.ConcurrencyAbstractionLayerImpl.<>c__DisplayClasse.<QueueUserWorkItem>b__d(Object _)
   at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadPool.WorkItem.doWork(Object o)
   at System.Threading.Timer.ring()
4

1 回答 1

0

Http 是异步使用的——你必须EndGetResponse在方法的回调(第一个参数)中调用BeginGetResponse。您的代码EndGetResponse在响应未准备好时调用。

查看本网站末尾的示例:http: //msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=vs.95%29.aspx

也许这个 http 类可以帮助您进行 http 调用:http: //mytoolkit.codeplex.com/wikipage ?title=Http

于 2012-08-21T22:52:22.633 回答