如何响应文件流和json对象作为Web API的单一响应

时间:2017-11-11 00:11:43

标签: json asp.net-web-api asp.net-web-api2

Web API, 我当前的Web API正在响应具有2个属性的JSON对象,如下所示。 我:1,FieldName:somename

现在,需要在响应中包含一个FILE(.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;
}

1 个答案:

答案 0 :(得分:0)

使用Base64String转换文件找到解决方案并将其包含到JSON响应中。

由于