Web API 2,将字符串作为文件返回

时间:2017-01-17 22:04:51

标签: file asp.net-web-api2 httpresponse

我有一个Web API 2 POST端点,它接受一个参数,查询数据库并返回一个xml字符串作为响应。

public async Task<IHttpActionResult> Post(long groupId)
{
    People people = await _someService.GetPeople(groupId);
    XElement peopleXml = _xmlService.ConverToXml(people);
    return Ok(peopleXml);
}

如何将xml作为文件返回?

1 个答案:

答案 0 :(得分:0)

自己想出来,但我希望有一种更简单的方法 -

public async Task<IHttpActionResult> Post(long groupId)
{
    People people = await _someService.GetPeople(groupId);
    XElement peopleXml = _xmlService.ConverToXml(people);
    byte[] toBytes = Encoding.Unicode.GetBytes(peopleXml.ToString());

    var stream = new MemoryStream(toBytes);

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StreamContent(stream)
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.txt"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

    var response = ResponseMessage(result);
    return response;
}