如何响应文件流和 json 对象作为 Web API 的单一响应
How to response with file stream and json object as single response of web API
网络API,
我当前的网络 API 正在响应 JSON 具有 2 个属性的对象,如下所示。
我会:1,FieldName:somename
现在,需要在响应中包含一个文件 (.CERT) 以及现有的 JSON 属性。
如何实现?
[授权]
[Route("getfileAndProperties")]
public HttpResponseMessage GetTestFile()
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.cer");
var p = new Person() {Id=1,userField="name"};
//need to include this Person object into response along with file.
if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// Serve the file to the client
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 = "SampleImg";
}
return result;
}
找到使用 Base64String 转换文件并包含到 JSON 响应中的解决方案。
谢谢
网络API, 我当前的网络 API 正在响应 JSON 具有 2 个属性的对象,如下所示。 我会:1,FieldName:somename
现在,需要在响应中包含一个文件 (.CERT) 以及现有的 JSON 属性。
如何实现?
[授权]
[Route("getfileAndProperties")]
public HttpResponseMessage GetTestFile()
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.cer");
var p = new Person() {Id=1,userField="name"};
//need to include this Person object into response along with file.
if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// Serve the file to the client
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 = "SampleImg";
}
return result;
}
找到使用 Base64String 转换文件并包含到 JSON 响应中的解决方案。
谢谢