我有一个用HttpResponseMessage
返回文件的代码,我想添加联系人字符串,我该怎么做?
[HttpPost]
public IHttpActionResult GetPlaylistXml(int playlistId, [FromBody] JObject data)
{
....
var serializer = new XmlSerializer(typeof(playList));
using (var memStream = new MemoryStream())
{
serializer.Serialize(memStream, playList);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memStream.ToArray(), 0, (int)memStream.Length)
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = playlist.Title + ".xml"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = ResponseMessage(result);
return response;
}
}
答案 0 :(得分:1)
根据您的偏好以及可能基于现有平台的限制,有几种选择:
您可以按原样保留代码并从流中读取文件并从标题中读取文件名(我个人推荐这个,除非有一些限制阻止您这样做)
创建一个模型并以json格式返回:
import org.junit.Test;
import com.google.gson.*;
import static org.junit.Assert.*;
public class JsonTest {
private JsonObject parse(@Nonnull String json) throws JsonSyntaxException {
JsonElement res = new JsonParser().parse(json);
System.out.println(res);
if (!res.isJsonObject()) {
throw new JsonSyntaxException("Top level JSON object required");
}
return res.getAsJsonObject();
}
private static void assertThrows(Runnable r) {
try {
r.run();
fail();
} catch (JsonSyntaxException expected) {
// ok
}
}
@Test
public void testIt() {
assertThrows(() -> parse(""));
assertThrows(() -> parse("null"));
assertThrows(() -> parse("Abracadabra"));
assertThrows(() -> parse("[]"));
assertTrue(parse("{}").entrySet().isEmpty());
assertThrows(() -> parse("{a: }"));
assertThrows(() -> parse("{a: ,}"));
assertThrows(() -> parse("{a: 0,}"));
assertTrue(parse("{a: null}").get("a").isJsonNull());
assertEquals(0, parse("{a: 0}").get("a").getAsInt());
assertEquals("", parse("{a: ''}").get("a").getAsString());
assertEquals("", parse("{a: \"\"}").get("a").getAsString());
assertEquals(0, parse("{a: []}").get("a").getAsJsonArray().size());
//assertThrows(() -> parse("{a: [1,]}")); // TODO: this parses without error to {"a":[1,null]}
}
}
使您的端点更像REST,并有两个端点,一个用于检索有关播放列表的信息,另一个用于检索播放列表文件:
[HttpPost]
public IHttpActionResult GetPlaylistXml(int playlistId, [FromBody] JObject data)
{
....
var serializer = new XmlSerializer(typeof(playList));
using (var memStream = new MemoryStream())
{
serializer.Serialize(memStream, playList);
var returnModel = new
{
Title = playList.Title,
// either a byte array (which is converted to Base64, or the XML string)
Playlist = memStream.ToArray()
};
return Json(returnModel);
}
}
我希望这会有所帮助。