如何从c#进行HttpClient调用以从下面的代码中获得结果



下面是一个正在运行的Web服务,我可以使用swagger从apicontroller获取结果文件,但在从控制台应用程序调用以获取结果时遇到了问题。使用c#获取结果的HttpClient调用会是什么样子。

[HttpGet, Route("api/DownloadHl7/{securitykey}/{specimenid}")]
public IHttpActionResult GetFileForCustomer(string securitykey, string specimenid) {
if (securitykey != Constants.ApiToken)
return BadRequest();
var file = FileToByteArray(pathtohl7 + specimenid + ".HL7");
IHttpActionResult response;
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
responseMsg.Content = new ByteArrayContent(file);
responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/HL7");
response = ResponseMessage(responseMsg);
return response;
}
public byte[] FileToByteArray(string fileName) {
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName)) {
using (BinaryReader binaryReader = new BinaryReader(fs)) {
fileData = binaryReader.ReadBytes((int)fs.Length);
}
}
return fileData;
}

最后使用下面的代码使其工作,无需更改apicontroller代码,按原样工作。

这将把文件下载到以正确格式指示的本地目录中。

using (HttpClient client = new HttpClient()) {
var response = await client.GetStreamAsync(downloadurlurl + "securitykey" + "/" + "741562");
using (var fs = new FileStream(string.Format(@"C:Bill{0}.HL7", "741562"),
FileMode.CreateNew)) {
await response.CopyToAsync(fs);
}
}

最新更新