解析多部分响应C#.net标准



我调用API以获得类似的多部分响应

------------cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5
Content-Disposition: form-data; name="Filename"
PB020344.jpg
------------cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5
Content-Disposition: form-data; name="Filedata"; filename="PB020344.jpg"
Content-Type: application/octet-stream
BINARY DATA IS HERE
------------cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5
Content-Disposition: form-data; name="Upload"
Submit Query
------------cH2ae0GI3KM7GI3Ij5ae0ei4Ij5Ij5-

我的问题是在.net标准中有一种更简单的方法来提取数据,我有一个带有方法的类库

private static byte[] ParseResponse(
byte[] responseStreamBytes,
out List<string> responseHeaders,
ref int startIndex ) {
try {
const byte CR = (byte)'r';
const byte NEWLINE = (byte)'n';
const byte HYPHEN = (byte)'-';
List<string> responseFileParams = new List<string>();
int nonDicomCount = 0;
//Figure out start of pixel byte array           
for (int i = startIndex; i < responseStreamBytes.Length; i++) {
if (responseStreamBytes[i] == CR) {
if (responseStreamBytes[i + 1] == NEWLINE) {
string boundray = Encoding.UTF8.GetString(
responseStreamBytes,
startIndex,
i - startIndex);
responseFileParams.Add(boundray);
nonDicomCount += boundray.Length;
//Initial header and start of pixel data
//Skip rn
startIndex = i = i + 2;
if (boundray.Contains("Content-Location")) {
break;
}
}
}
}
responseHeaders = responseFileParams;
startIndex += 2;
//Keep count of non dicom data. Add 4 to skip CR
nonDicomCount = nonDicomCount + 4;
string endBoundary = responseFileParams[0]; // + "--";
List<byte> byteList = new List<byte>();
//Collect all pixel bytes in an array
for (int r = startIndex; r < responseStreamBytes.Length; r++) {
if (responseStreamBytes[r] == CR && responseStreamBytes[r + 1] == NEWLINE) {
if (
responseStreamBytes[r + 2] == HYPHEN &&
responseStreamBytes[r + 3] == HYPHEN
) {
//End of DICOM data
//r+2 to skip rn
string endBoundaryInArray = Encoding.UTF8.GetString(
responseStreamBytes,
r + 2,
endBoundary.Length);
if (
string.Compare(
endBoundary,
endBoundaryInArray,
StringComparison.OrdinalIgnoreCase) == 0
) {
startIndex = r + 2;
break;
}
}
}
byteList.Add(responseStreamBytes[r]);
}
return byteList.ToArray();
} catch (Exception e) {

responseHeaders = new List<string>();
return responseStreamBytes;
}
}

我想知道是否在.net标准中,或者有一种更简单的方法来提取字节数据

有一个名为Http Multipart Data Parser的开源库可以帮助您做到这一点。您可以从NuGet下载并安装它。这是我在使用Grapevine的项目中使用并推荐的解析器。

相关内容

  • 没有找到相关文章

最新更新