c# HttpClient 解析来自 webservice 的响应

c# HttpClient Parse response from webservice

我正在调用一个超级旧的外部网络服务,它在响应中包含 CSV 值:

--XXXXXXX_0d5d4bd4-93a4-11ec-8139-00000611f70a_END
Content-ID: <payload-621420A61A932740E10080DB995F3244@XXXXXXX.XXX>
Content-Disposition: form-data;filename="MainDocument.bin";name="MainDocument"
Content-Type: application/json
Content-Description: MainDocument

{"mt_csvfile":"csvfile.csv"}
--XXXXXXX_0d5d4bd4-93a4-11ec-8139-00000611f70a_END
Content-ID: <csvfile.csv>
Content-Disposition: form-data;filename="csvfile.csv";name="csvfile.csv"
Content-Type: mimeType text/comma-separated-values;charset="uft-8"
Content-Description: csvfile.csv

"NUMBER","DESCRIPTION",
"00000000001","DESC 1",
"00000000002","DESC 2",
"00000000003","DESC 3",

--XXXXXXX_0d5d4bd4-93a4-11ec-8139-00000611f70a_END--

我只关心 CSV 负载。

如何解析响应? 我不是在问如何解析 CSV 文件。

我正在使用 httpClient:

var client = new HttpClient();
client.BaseAddress = new Uri("<BASEURL>");

using var content = new MultipartFormDataContent();
var uri = new Uri(client.BaseAddress, "<ENDPOINT>");
var response = await client.PostAsync(uri, content);

response.EnsureSuccessStatusCode();

using (Stream responseStream = await response.Content.ReadAsStreamAsync())
{
    // need to get CSV values only
}

最后我用 Http-Multipart-Data-Parser. Credits go to nazarn 提示没有默认解决方案并使用了一个包。

var client = new HttpClient();
client.BaseAddress = new Uri("<BASEURL>");

using var content = new MultipartFormDataContent();
var uri = new Uri(client.BaseAddress, "<ENDPOINT>");
var response = await client.PostAsync(uri, content);

response.EnsureSuccessStatusCode();

using (Stream stream = await response.Content.ReadAsStreamAsync())
{
    var parser = await MultipartFormDataParser.ParseAsync(stream);

    // CSV contents in Last file
    var file = parser.Files.Last();
    string filename = file.FileName;
    Stream data = file.Data;

    using (Stream fileStream = File.Create($@"C:\temp\{filename}"))
    {
        data.Seek(0, SeekOrigin.Begin);
        data.CopyTo(fileStream);
    }
}