我正在使用“发布”方法,因此我可以发送自定义对象。但是我一直在request.BeginGetResponse():
上得到以下异常{System.Net.ProtocolViolationException:由于对象的当前状态,操作无效。 在System.Net.Browser.BrowserHttpWebRequest.BeginGetResponseImplementation()}
public void Send()
{
HttpWebRequest client = WebRequest.Create(new Uri(BaseUrl)) as HttpWebRequest;
client.Method = "POST";
client.ContentLength = MaxSerializationSize;
client.BeginGetRequestStream(new AsyncCallback(RequestProceed), client);
}
private void RequestProceed(IAsyncResult asuncResult)
{
HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;
StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyCustomClass));
ser.WriteObject(ms, MyCustomClassObject);
postDataWriter.Write(ms);
postDataWriter.Close();
request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);
}
private void ResponceProceed(IAsyncResult asuncResult)
{
var request = (HttpWebRequest) asuncResult.AsyncState;
using (var resp = (HttpWebResponse) request.EndGetResponse(asuncResult))
{
using (var stream = resp.GetResponseStream())
{
}
}
}
我已经尝试了很多方法让它发挥作用。希望有人能告诉我哪里出错了。谢谢。
答案 0 :(得分:2)
您需要关闭请求流。您只是关闭StreamWriter
而不是基础请求流。当你在它时,消除了超级MemoryStream
并让DataContractJsonSerializer
直接写入请求流。
HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;
using (Stream outStream = request.EndGetRequestStream(asyncResult));
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyCustomClass));
ser.WriteObject(outStream, MyCustomClassObject);
outStream.Flush();
outStream.Close();
}
request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);
也摆脱这一行: -
client.ContentLength = MaxSerializationSize;
在不关闭AllowWriteStreamBuffering
的情况下(只有在ClientHTTP
实施时才可以),无需设置ContentLength
,这是为您完成的。