如何在.NET Framework 3.5中提交JSON并获取返回的文件流?
.NET Framework 3.5 Client for Web API 2: Submit JSON & Download File Stream
Got it, let's work through building this .NET 3.5 client since HttpClient isn't available until .NET 4.5. We'll extend WebClient to handle JSON payloads properly and capture the download stream from your API.
Step 1: Create a Custom WebClient for JSON Requests
The default WebClient doesn't make it easy to set the Content-Type header to application/json, so we'll subclass it to override the request setup:
using System.Net; using System.Text; public class JsonWebClient : WebClient { protected override WebRequest GetWebRequest(System.Uri address) { WebRequest request = base.GetWebRequest(address); if (request is HttpWebRequest httpRequest) { httpRequest.ContentType = "application/json; charset=utf-8"; } return request; } }
Step 2: Implement the Full JSON Submit & File Download Flow
We'll serialize your JObject to a JSON string, send it via POST, then read the response stream to save the file. Note: You'll need the Newtonsoft.Json (Json.NET) NuGet package (version compatible with .NET 3.5) to handle JObject serialization.
using Newtonsoft.Json; using System.IO; public void SubmitJsonAndDownloadFile(string apiUrl, JObject jsonPayload, string outputFilePath) { using (var jsonClient = new JsonWebClient()) { try { // Serialize JObject to JSON string string jsonString = JsonConvert.SerializeObject(jsonPayload); byte[] postData = Encoding.UTF8.GetBytes(jsonString); // Send POST request to the API jsonClient.UploadData(apiUrl, "POST", postData); // Retrieve the response stream and save to file using (Stream responseStream = jsonClient.OpenRead(apiUrl)) using (Stream fileStream = File.Create(outputFilePath)) { // .NET 3.5 doesn't have Stream.CopyTo, so we'll do a manual copy byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } Console.WriteLine("File downloaded successfully!"); } catch (WebException ex) { // Handle API errors (e.g., invalid JSON, validation failures) using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream())) { string errorResponse = reader.ReadToEnd(); Console.WriteLine($"API Error: {errorResponse}"); } throw; } catch (Exception ex) { Console.WriteLine($"General Error: {ex.Message}"); throw; } } }
Key Notes for .NET 3.5:
- Json.NET Dependency: .NET 3.5 doesn't have built-in JSON serialization for
JObject, so install a compatible version of Newtonsoft.Json (v10.0.3 is the last official release supporting .NET 3.5). - Manual Stream Copy: Since
Stream.CopyTo()wasn't added until .NET 4.0, we use a buffer to read/write the stream manually. - Error Handling:
WebExceptionlets you access the API's error response body—your service might return validation details as JSON even when it returns a non-200 status code.
Example Usage
// Build your request JSON JObject requestJson = new JObject(); requestJson["documentId"] = "12345"; requestJson["validationRules"] = new JArray("checksum", "expiry"); // Call the method to submit JSON and download the file SubmitJsonAndDownloadFile("https://your-api-endpoint.com/api/download", requestJson, @"C:\Downloads\result.pdf");
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

