Set CSV MediaTypeHeaderValue in .NET
How to set a text/csv content type with MediaTypeHeaderValue in .NET, what the header changes and what it doesn't, and how to keep CSV files usable once they are downloaded.
When a .NET application sends or returns CSV data, the HTTP Content-Type header tells the receiver how to interpret the bytes. In .NET that header is usually represented by a MediaTypeHeaderValue object. This review covers how to set a CSV media type correctly, what the header actually controls, and where problems tend to come from: character encoding and the program that opens the file, not the header itself.
Is text/csv the right choice for your use?
Use text/csv when the payload is genuinely comma-separated data meant to be parsed, imported or saved as a file. The main benefit is that clients, browsers and integration code get an accurate signal about the format and can choose a parser, a file extension or a download action. The decisive tradeoff is that the header describes the data. It does not make the data valid CSV. If the content has inconsistent quoting, mixed delimiters or an undeclared encoding, a correct header will not fix that.
Plain text (text/plain) is often the better choice when the output is meant to be read by people inline, such as a diagnostic dump or log-style listing. It also fits when the content is only loosely tabular and does not follow CSV quoting rules. For tab-separated data, the registered type is text/tab-separated-values, not text/csv.
Which MediaTypeHeaderValue class you are using
Two classes in .NET share the name MediaTypeHeaderValue, and both work for CSV:
- System.Net.Http.Headers.MediaTypeHeaderValue: used with HttpClient, HttpContent and HttpResponseMessage, including classic ASP.NET Web API.
- Microsoft.Net.Http.Headers.MediaTypeHeaderValue: used inside ASP.NET Core for parsing and formatting headers. It works with StringSegment values rather than plain strings in several members.
Check your using directives if a compiler error mentions an ambiguous reference or a missing property. Both classes expose a media type and a charset, but their APIs are not identical.
Setting the header with HttpClient
When posting CSV to an API, you can pass the media type string straight to StringContent, or assign a MediaTypeHeaderValue to set the charset explicitly:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var content = new StringContent(csv, Encoding.UTF8, "text/csv");
// Or set the header object directly
content.Headers.ContentType = new MediaTypeHeaderValue("text/csv")
{
CharSet = "utf-8"
};
var response = await client.PostAsync(uploadUri, content);
To ask a server for CSV instead of its default format, add an Accept header. Accept headers use the quality-aware subclass:
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("text/csv"));
If you already have a full header string, MediaTypeHeaderValue.Parse("text/csv; charset=utf-8") produces the same object. TryParse avoids exceptions when the value comes from untrusted input.
Returning CSV from ASP.NET Core
In ASP.NET Core you rarely need to construct the header object yourself. The result helpers accept a content type string and set the header for you:
// Controller action: download as a file
var bytes = Encoding.UTF8.GetBytes(csv);
return File(bytes, "text/csv", "report.csv");
// Minimal API: return as text with an explicit encoding
app.MapGet("/report", () =>
Results.Text(csv, "text/csv", Encoding.UTF8));
Supplying a file name to File() also adds a Content-Disposition header, which signals that the response should be saved rather than shown. Some versions of .NET include named constants for common media types in System.Net.Mime.MediaTypeNames. Check whether a CSV constant exists for your target framework before relying on it; the literal string "text/csv" works everywhere.
Returning CSV from classic ASP.NET Web API
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(csv))
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { FileName = "report.csv" };
return result;
What setting the media type actually changes
Setting the media type changes metadata only. Assigning text/csv writes a Content-Type line into the HTTP message. It does not convert, reorder or re-encode a single byte of the body. The bytes are set separately, by whatever encoding you pass to StringContent, Encoding.GetBytes or the response writer. Many CSV problems come from a mismatch between the two layers. Typical examples are a header that declares charset=utf-8 over a body encoded differently, or a header that says text/csv over a body that is really JSON or HTML.
| Layer | Controlled by | Effect |
| Content-Type header | MediaTypeHeaderValue, or a content type string | Tells the receiver the format and charset |
| Charset parameter | CharSet property, or charset= in the string | Declares how text bytes should be decoded |
| Body bytes | Encoding passed when creating the content | The actual characters the receiver gets |
| Content-Disposition | ContentDispositionHeaderValue, or a file name argument | Suggests download and a file name |
The CSV format is described in RFC 4180, which registers text/csv. That document uses CRLF line endings and double-quote escaping, and defines optional charset and header parameters for the media type. Following those conventions in the body matters more for interoperability than any header detail.
Will the file stay readable after download or sharing?
CSV is plain text, so once saved it can be copied, searched, edited and versioned like any text file. Whether it stays readable depends on the program that opens it:
- Encoding: Encoding.UTF8.GetBytes and StringContent do not prepend a byte order mark. Some spreadsheet applications are commonly reported to misread non-ASCII characters in UTF-8 CSV files that lack one. Test the specific application and version your readers use before adding Encoding.UTF8.GetPreamble() to the output.
- Delimiters and locale: some spreadsheet programs expect a semicolon instead of a comma in regions that use the comma as a decimal separator. The header cannot communicate this.
- Browser handling: whether a browser displays text/csv inline or downloads it varies by browser and settings. Add a Content-Disposition attachment header if you need a predictable download.
- Formulas in cells: values beginning with characters such as = can be interpreted as formulas when opened in a spreadsheet. If the data comes from users, review how your export handles this.
Accessibility depends mostly on the application that opens the file. A screen reader reads CSV opened in a text editor as raw delimited lines. In a spreadsheet, the same data becomes navigable rows and columns. No documentation or tests for specific assistive technologies were available for this review, so check them with your actual audience. If people need to read the data without software that parses CSV, provide an HTML table or a plain-text summary alongside the file.
Evidence and gaps
The code above reflects the documented APIs of the .NET HTTP and ASP.NET libraries and the general conventions of RFC 4180. No measurements, compatibility tests or version-specific results were provided for this review, and none are claimed. Spreadsheet behavior with byte order marks, browser download handling and screen reader output vary by environment. Confirm them in the setups your users actually have.