如何另外包含文件作为 WebAPI 的响应
How to additionally include File as response of WebAPI
我当前的网站 API 已经响应 JSON 如下数据。
public HttpResponseMessage GetFieldInfo()
{
//....
return Ok(GetFieldsInstance()); //GetFieldsInstance returning with DTO class instance.
}
现在,我需要包含文件以及 JSON 响应。我找不到任何显示如何在单个响应中包含文件流和 JSON 的 link。
对于文件流,它将按以下方式工作,但无法找到如何将 JSON 对象 属性 包含在文件流中的方法。
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "FieldFile";
您可以将文件转换(序列化)为 base64 字符串,并将其作为 属性 包含在 JSON 响应中。
public IHttpActionResult GetFieldInfo() {
//...
var model = new {
//assuming: byte[] GetBinaryFile(...)
data = Convert.ToBase64String(GetBinaryFile(localFilePath)),
result = "final",
//...other properties...
};
return Ok(model);
}
然后客户端需要将 base64 字符串转换(反序列化)回您想要的文件,以便按需要使用。
请注意,根据文件的大小,它可能会大大增加响应的大小,客户端应考虑到这一点。
我当前的网站 API 已经响应 JSON 如下数据。
public HttpResponseMessage GetFieldInfo()
{
//....
return Ok(GetFieldsInstance()); //GetFieldsInstance returning with DTO class instance.
}
现在,我需要包含文件以及 JSON 响应。我找不到任何显示如何在单个响应中包含文件流和 JSON 的 link。
对于文件流,它将按以下方式工作,但无法找到如何将 JSON 对象 属性 包含在文件流中的方法。
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "FieldFile";
您可以将文件转换(序列化)为 base64 字符串,并将其作为 属性 包含在 JSON 响应中。
public IHttpActionResult GetFieldInfo() {
//...
var model = new {
//assuming: byte[] GetBinaryFile(...)
data = Convert.ToBase64String(GetBinaryFile(localFilePath)),
result = "final",
//...other properties...
};
return Ok(model);
}
然后客户端需要将 base64 字符串转换(反序列化)回您想要的文件,以便按需要使用。
请注意,根据文件的大小,它可能会大大增加响应的大小,客户端应考虑到这一点。