1

我有一个 C# .net Web 应用程序。我正在尝试使用此代码将二进制数据从一个应用程序发布到另一个应用程序

    string url = "path to send the data";

    string result=null;
    string postData = "This is a test that posts this string to a Web server.";
    byte[] fileData = Encoding.UTF8.GetBytes (postData);

    // Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create (url);
    // Set the Method property of the request to POST.
    request.Method = "POST";
    // Create POST data and convert it to a byte array.    

    // Set the ContentType property of the WebRequest.
    request.ContentType = "multipart/form-data";
    // Set the ContentLength property of the WebRequest.
    request.ContentLength = fileData.Length;
    // Get the request stream.
    Stream dataStream = request.GetRequestStream ();
    // Write the data to the request stream.
    dataStream.Write (fileData, 0, fileData.Length);
    // Close the Stream object.
    dataStream.Close ();
    // Get the response.
    WebResponse response = request.GetResponse();
    // Display the status.

    result = ((HttpWebResponse)response).StatusDescription;
    // Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream ();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader (dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd ();
    // Display the content.

    result = result + responseFromServer;
    // Clean up the streams.
    reader.Close ();
    dataStream.Close ();
    response.Close();

通过上面的代码,我发送byte[]到第二个应用程序。如何byte[]在第二个应用程序中检索发布的数据(格式)?

4

2 回答 2

1

编辑:更新的答案包括请求和服务器端。服务器端将 Base64 字符串转换为byte[].

如果您要发布读入字节 [] 的二进制数据,则必须在请求端将其转换为 Base64 字符串才能发布。

客户端/请求方:

byte[] byteData = ReadSomeData();

string postData = Convert.ToBase64String(byteData);

然后在服务器端,使用HttpContext从 Request 属性中获取 InputStream。然后,您可以使用 aStreamReader及其 ReadToEnd() 方法来读取数据。然后将发布的 Base64 字符串转换为byte[].

像这样的东西:

string postData = string.Empty;

using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
    postData = inputStreamReader.ReadToEnd();
}

byte[] data = Convert.FromBase64String(postData);
于 2013-04-04T13:21:09.497 回答
1

注意:我假设您正在询问如何在第二个应用程序中检索发布的数据,并且您可以访问第二个应用程序的代码。

然后,如果它是一个网络表单应用程序,那么只需在 page_load 事件上,您就可以获得文件名和文件本身:

string strFileName = Request.Files[0].FileName;
HttpPostedFileBase filesToSave = Request.Files[0];

如果这不是要求,请编辑您的问题并添加更多详细信息。

于 2013-04-04T10:34:09.693 回答