我正在尝试对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()
答案 0 :(得分: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