0

再会。

我想要做的是在客户端应用程序和 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字符串或给出如何正确处理这种情况的建议。谢谢你。

4

1 回答 1

0

您的 500 错误消息是通用 IIS 消息而不是 ASP.Net 消息吗?如果是这样,那可能意味着数据甚至没有到达 ASP.Net 并且 IIS 正在阻塞它。我的第一个猜测是您遇到了上传限制。这是在 IIS 6 中增加它的一种方法。设置 IIS 后,您还必须更改 ASP.Net 的值。至于您的其他错误,您应该真正考虑捕获它们。.Net 框架很好地解释了哪里出了问题。

于 2011-01-03T17:51:46.517 回答