EndGetResponse中抛出NotSupportedException(request.BeginGetResponse(null,null)))

时间:2013-09-09 13:58:17

标签: c# exception windows-phone-8 httpwebrequest notsupportedexception

我有以下代码使异步调用同步。

请注意,这不是很糟糕,我知道,只有一个特定的请求需要这样做。

当执行using(var response = request.EndGetResponse(request.BeginGetResponse(null,null)))时,代码在Windows Phone 8中引发异常。

实际上,在UnhandledException事件处理程序中调用了该请求。

例外:NotSupportedException

消息:Method is not supported

堆栈跟踪:

  

在   System.Net.Browser.ClientHttpWebRequest.BeginGetResponse(AsyncCallback的   回调,对象状态)at   Gtas.Core.ServiceRepository.ExecuteGtasRequest(String url,String   requestData,Boolean isError,String filePath)at   Gtas.Core.Helpers.GtasRequestWorker.HandleException(例外   例外,AppEnvironment appEnvironment,GtasPerformance   GtasPerformance,LimitedCrashExtraDataList extraData,String filePath)   在Gtas_WP8.GtasHandler.UnhandledExceptionsHandler(对象发送者,   ApplicationUnhandledExceptionEventArgs e)at   MS.Internal.Error.CallApplicationUEHandler(Exception e)at   MS.Internal.Error.IsNonRecoverableUserException(Exception ex,UInt32&   xresultValue)

public void ExecuteRequest(string url, string requestData)
{
    try
    {
        WebRequest request = WebRequest.Create(new Uri(url));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Headers["Header-Key"] = "AKey";

        // Convert the string into a byte array.
        byte[] postBytes = Encoding.UTF8.GetBytes(requestData);

        using (var requestStream = request.EndGetRequestStream(request.BeginGetRequestStream(null, null)))
        {
            // Write to the request stream.
            endGetRequestStream.Write(postBytes, 0, postBytes.Length);
        }

        using (var response = request.EndGetResponse(request.BeginGetResponse(null, null))) // NotSupportedException
        {
            using (var streamRead = new StreamReader(response.GetResponseStream()))
            {
                // The Response
                string responseString = streamRead.ReadToEnd();

                if (!string.IsNullOrWhiteSpace(requestDataObjResult.FileName))
                {
                    var fileRepo = new FileRepository();
                    fileRepo.Delete(request.FileName);
                }

                Debug.WriteLine("Response : {0}", responseString);
            }
        }
    }
    catch (WebException webEx)
    {
        WebExceptionStatus status = webEx.Status;
        WebResponse responseEx = webEx.Response;
        Debug.WriteLine(webEx.ToString());
    }    
}

框架是否有可能不允许这样做?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

在调用EndGetResponse之前,您是否需要等到BeginGetResponse完成?这可能导致NotSupportedException。

此外,我遇到了类似的问题。当我尝试使用null的回调调用BeginGetResponse时,抛出了NotSupportedException。我只是通过定义这个

来解决这个问题
   (a)=>{}

作为回调。 (那是银光)

此致

了Christoph