ServiceStack CSV Format

Demis Bellot edited this page Dec 3, 2013 · 1 revision

#ServiceStack's CSV Format

The CSV format is now a first-class supported format which means all your existing web services can automatically take advantage of the new format without any config or code changes. Just drop the latest ServiceStack.dlls (v1.77+) and you're good to go!

Importance of CSV

CSV is an important format for transferring, migrating and quickly visualizing data as all spreadsheets support viewing and editing CSV files directly whilst its supported by most RDBMS support exporting and importing data. Compared with other serialization formats, it provides a compact and efficient way to transfer large datasets in an easy to read text format.


The CSV Serializer used was developed using the same tech that makes ServiceStack's JSV and JSON serializers fast (i.e. no run-time reflection, static delegate caching, etc), which should make it the fastest CSV serializer available for .NET.

Downloadable Separately

The CsvSerializer is maintained in the ServiceStack.Text project and is available as a separate download for use in your own .NET projects.

How to register your own custom format with ServiceStack

What makes the 'CSV' format different is its the first format added using the new extensions API. The complete code to register the CSV format is:

//Register the 'text/csv' content-type and serializers (format is inferred from the last part of the content-type)
	CsvSerializer.SerializeToStream, CsvSerializer.DeserializeFromStream);

//Add a response filter to add a 'Content-Disposition' header so browsers treat it natively as a .csv file
this.ResponseFilters.Add((req, res, dto) =>
		if (req.ResponseContentType == ContentType.Csv)
				string.Format("attachment;filename={0}.csv", req.OperationName));

Note: ServiceStack already does this for you though it still serves a good example to show how you can plug-in your own custom format. If you wish, you can remove all custom formats with (inside AppHost.Configure()): this.ContentTypeFilters.ClearCustomFilters();

The ability to automatically to register another format and provide immediate value and added functionality to all your existing web services (without any code-changes or configuration) we believe is a testament to ServiceStack's clean design of using strongly-typed 'message-based' DTOs to let you develop clean, testable and re-usable web services. No code-gen or marshalling is required to bind to an abstract method signature, every request and calling convention maps naturally to your webservices DTOs.


The CSV format is effectively a first-class supported format so everything should work as expected, including being registered as an available format on ServiceStack's metadata index page:

And being able to preview the output of a service:

By default they are automatically available using ServiceStack's standard calling conventions, e.g:

REST Usage

CSV also works just as you would expect with user-defined REST-ful urls, i.e. you can append ?format=csv to specify the format in the url e.g:

This is how the above web service output looks when opened up in google docs

Alternative in following with the HTTP specification you can also specify content-type "text/csv" in the Accept header of your HttpClient, e.g:

var httpReq = (HttpWebRequest)WebRequest.Create("");
httpReq.Accept = "text/csv";
var csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();


As most readers familiar with the CSV format will know there are some inherent limitations with CSV-format namely it is a flat-structured tabular data format that really only supports serialization of a single resultset.

This limitation remains, although if you decorate your Response DTO with a [Csv(CsvBehavior.FirstEnumerable)] or standard .NET [DataContract]/[DataMember] attributes the CSV Serializer will change to use the following conventions:

  • If you only return one result in your DTO it will serialize that.
  • If you return multiple results it will pick the first IEnumerable<> property or if it doesn't exist picks the first property.
  • Non-enumerable results are treated like a single row.

Basically if you only return 1 result it should work as expected otherwise it will chose the best candidate based on the rules above.

The second major limitation is that it doesn't yet include a CSV Deserializer (currently on the TODO list), so while you can view the results in CSV format you can't post data to your web service in CSV and have it automatically deserialize for you. You can however still upload a CSV file and parse it manually yourself.

#Features Unlike most CSV serializers that can only serialize rows of primitive values, the CsvSeriliaizer uses the JSV Format under the hood so even complex types will be serialized in fields in a easy to read format - no matter how deep its heirachy.

Feel free to discuss or find more about any of these features at the Service Stack Google Group

<Wiki Home

  1. Getting Started
    1. Create your first webservice
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
  2. Reference
    1. Order of Operations
    2. The IoC container
    3. Metadata page
    4. Rest, SOAP & default endpoints
    5. SOAP support
    6. Routing
    7. Service return types
    8. Customize HTTP Responses
    9. Plugins
    10. Validation
    11. Error Handling
    12. Security
  3. Clients
    1. Overview
    2. C# client
    3. Silverlight client
    4. JavaScript client
    5. Dart Client
    6. MQ Clients
  4. Formats
    1. Overview
    2. JSON/JSV and XML
    3. ServiceStack's new HTML5 Report Format
    4. ServiceStack's new CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  5. View Engines 4. Razor & Markdown Razor
    1. Markdown Razor
  6. Hosts
    1. IIS
    2. Self-hosting
    3. Mono
  7. Security
    1. Authentication/authorization
    2. Sessions
    3. Restricting Services
  8. Advanced
    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in caching options
    9. Built-in profiling
    10. Messaging and Redis
    11. Form Hijacking Prevention
    12. Auto-Mapping
    13. HTTP Utils
    14. Virtual File System
    15. Config API
    16. Physical Project Structure
    17. Modularizing Services
    18. MVC Integration
  9. Plugins 3. Request logger 4. Swagger API
  10. Tests
    1. Testing
    2. HowTo write unit/integration tests
  11. Other Languages
    1. FSharp
    2. VB.NET
  12. Use Cases
    1. Single Page Apps
    2. Azure
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  13. Performance
    1. Real world performance
  14. How To
    1. Sending stream to ServiceStack
    2. Setting UserAgent in ServiceStack JsonServiceClient
    3. ServiceStack adding to allowed file extensions
    4. Default web service page how to
  15. Future
    1. Roadmap
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.