再会。
我想要做的是在客户端应用程序和 asp.net 页面之间交换序列化数据。
我使用以下类进行交换:
public class Send
{
public Guid guidField;
public string stringField1;
public string stringField2;
public byte[] data;
}
和
public class Receive
{
public Guid guidField;
public byte[] data;
}
在客户端,我使用以下代码发出请求:
public Receive Exchange(Send send)
{
Receive receive = new Receive();
string address = "example.org";
HttpWebRequest client = (HttpWebRequest)WebRequest.Create(address);
client.ContentType = "application/x-www-form-urlencoded";
client.Timeout = 90000;
client.Method = "POST";
client.UserAgent = "AgentMe";
try
{
Stream stream = client.GetRequestStream();
PackSend(stream, send);
stream.Flush();
stream.Close();
var response = client.GetResponse();
Stream outputStream = response.GetResponseStream();
UnpackReceive(outputStream, out receive);
}
catch (WebException ex)
{ }
return receive;
}
在服务器端,我以类似的方式执行此操作,但方向相反:
protected void Page_Load(object sender, EventArgs e)
{
Stream inputStream = Request.InputStream;
Send send;
UnpackSend(inputStream, out send);
// here goes some useful work
Receive receive = Process(send);
Response.ContentType = "application/x-www-form-urlencoded";
Stream stream = Response.OutputStream;
PackReceive(stream, sent);
Response.End();
}
对于打包和解包数据,我使用 Newtonsoft.Json :
static void PackSend(Stream stream, Send message)
{
BsonWriter writer = new BsonWriter(stream);
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, message);
writer.Flush();
writer.Close();
}
void UnpackSend(Stream stream, out Send message)
{
BsonReader reader = new BsonReader(stream);
JsonSerializer serializer = new JsonSerializer();
message = serializer.Deserialize<Send>(reader);
}
PackReceive/UnpackReceive 的代码类似。
当我使用时ContentType = "application/x-www-form-urlencoded"
,我可以进行交换,但前提是public byte[] data
字段大小不超过 ~1200 字节。如果大小更大,我收到内部服务器错误 500 请求。
使用ContentType = "text/xml"
; 在服务器端正确处理任何大小的“公共字节 [] 数据”字段。有用的工作已经完成,但是当服务器尝试写入响应流时,我猜会发生错误并自动重复请求,因此客户端应用程序被卡住,用多个类似的请求淹没服务器而不会引发任何错误。
ContentType = "application/octet-stream"
- 显示与“text/xml”相同的行为。
任何人都可以建议一个适当的ContentType
字符串或给出如何正确处理这种情况的建议。谢谢你。