-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathCsvFormat.cs
More file actions
52 lines (49 loc) · 1.79 KB
/
Copy pathCsvFormat.cs
File metadata and controls
52 lines (49 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.IO;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack.Formats
{
public class CsvFormat : IPlugin, Model.IHasStringId
{
public string Id { get; set; } = Plugins.Csv;
public void Register(IAppHost appHost)
{
//Register the 'text/csv' content-type and serializers (format is inferred from the last part of the content-type)
appHost.ContentTypes.Register(MimeTypes.Csv,
SerializeToStream, CsvSerializer.DeserializeFromStream);
//Add a response filter to add a 'Content-Disposition' header so browsers treat it natively as a .csv file
appHost.GlobalResponseFilters.Add((req, res, dto) =>
{
if (req.ResponseContentType == MimeTypes.Csv && dto is not IHttpResult) //avoid double Content-Disposition headers
{
var fileName = req.OperationName + ".csv";
res.AddHeader(HttpHeaders.ContentDisposition, $"attachment;{HttpExt.GetDispositionFileName(fileName)}");
}
});
}
public void SerializeToStream(IRequest req, object request, Stream stream)
{
if (request is string str)
{
stream.Write(str);
}
else if (request is byte[] bytes)
{
stream.Write(bytes, 0, bytes.Length);
}
else if (request is Stream s)
{
s.WriteTo(stream);
}
else if (request is ReadOnlyMemory<char> roms)
{
MemoryProvider.Instance.Write(stream, roms);
}
else
{
CsvSerializer.SerializeToStream(request, stream);
}
}
}
}