dataStream.Length'引发了类型为'System.NotSupportedException的异常

dataStream.Length'引发了类型为'System.NotSupportedException的异常

问题描述:

大家好,

我必须使用HTTP发布将一些数据从asp.net发布到Web服务.

当我尝试将数据发布到Restful服务并遇到此错误时.任何帮助,不胜感激.

Hi All,

I have to post some data from asp.net to Webservice using HTTP post.

While I am trying to POST data to a Restful service and getting this error. Any help greatly appreciated.

Length = 'dataStream.Length' threw an exception of type 'System.NotSupportedException'

Position = 'dataStream.Position' threw an exception of type 'System.NotSupportedException'


以下是我的代码.


Below is my code.

protected string GetResponseWithPost(string StrURL, string strPostData)
    {
        string strReturn = "";
        HttpWebRequest objRequest = null;
        ASCIIEncoding objEncoding = new ASCIIEncoding();
        Stream reqStream = null;
        HttpWebResponse objResponse = null;
        StreamReader objReader = null;
        try
        {
            objRequest = (HttpWebRequest)WebRequest.Create(StrURL);

            objRequest.Method = "POST";
            byte[] objBytes = objEncoding.GetBytes(strPostData);
            objRequest.ContentLength = objBytes.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";
            reqStream = objRequest.GetRequestStream();
            reqStream.Write(objBytes, 0, objBytes.Length);

            IAsyncResult ar = objRequest.BeginGetResponse(new AsyncCallback(GetScrapingResponse), objRequest);
            //// Wait for request to complete
            ar.AsyncWaitHandle.WaitOne(1000 * 60 * 3, true);
            if (objRequest.HaveResponse == false)
            {
                throw new Exception("No Response!!!");
            }
            objResponse = (HttpWebResponse)objRequest.EndGetResponse(ar);
            objReader = new StreamReader(objResponse.GetResponseStream());
            strReturn = objReader.ReadToEnd();

        }
        catch (Exception exp)
        {
            throw exp;
        }
        finally
        {
            objRequest = null;
            objEncoding = null;
            reqStream = null;
            if (objResponse != null)
                objResponse.Close();
            objResponse = null;
            objReader = null;
        }
        return strReturn;
    }


提前谢谢.

Priyanka


Thanks in advance.

Priyanka


如果可以确定在哪一行出现了错误,但查看代码似乎正在尝试以同步方式处理异步调用,这将很有帮助.

您应该从回调中调用EndGetResponce,因此请确保可以从这两种方法(安全地)访问数据缓冲区.

希望这会有所帮助.

干杯,AT
Hi,
It would help if you could identify on what line you got the error but looking at the code it seem that you are trying to handle a async call in a synchrounous way.

You should call the EndGetResponce from the callback and as such make sure that the data buffer can be accessed (safely) from both methods.

Hope this helps.

Cheers, AT