MIME types
A MIME type names the kind of a piece of data — text/html, image/png, application/json. A server sends it so that the browser knows what to do with the bytes, and a client sends a list of types it understands. This lesson maps file names to types, reads a Content-Type header, and chooses what to send for an Accept header.
What you will learn#
- what a MIME type (media type, content type) is,
- mapping file extensions to types (
FileExtensionContentTypeProvider), - adding a type of your own,
- reading
Content-Type(type, subtype,charset), - the
Acceptheader, quality values and wildcards, - content negotiation and the answer 406 Not Acceptable.
The tutorial HTTP and the tutorial HttpClient in depth used HTTP from the client side and the tutorial A tiny web framework from the server side. Whenever a body is sent, a type must say what it is.
The content type classes (Microsoft.AspNetCore.StaticFiles, Microsoft.Net.Http.Headers) are part of the ASP.NET Core runtime, so the program has "RingDotNet.Web" in its using { } (Getting started).
The program#
# MIME types - file extensions to content types, reading a Content-Type header, and choosing what to send for an Accept header
load "dotnet.ring"
using {
"Microsoft.Net.Http.Headers"
"Microsoft.AspNetCore.StaticFiles"
"System"
"System.Net.Mime"
"RingDotNet.Web" # the content type classes of ASP.NET Core are part of its runtime: this line starts it
}
func main
# A MIME type (media type, content type) names the KIND of a piece of data: text/html, image/png, application/json. A server sends it in
# the Content-Type header so that the browser knows what to do with the bytes, and a client sends Accept to say what it understands.
# 1. From a file name to a type. The provider knows the common extensions.
oProvider = new FileExtensionContentTypeProvider
? "1. file name -> content type:"
for cFile in ["index.html","logo.png","photo.JPG","data.json","report.pdf","archive.zip","notes.txt","song.mp3","movie.mp4","style.css","app.js","unknown.xyz123"]
? " " + padRight(cFile,16) + contentTypeOf(oProvider,cFile)
next
# 2. The mapping can be extended: a type of your own for your own extension
oProvider.Mappings.Add(".ring","text/x-ring")
? nl + "2. after adding .ring: " + contentTypeOf(oProvider,"program.ring")
? " (a file with an unknown type is sent as application/octet-stream: 'some bytes, download them')"
# 3. Reading a Content-Type header: the type, the subtype and the parameters (the charset says how text is encoded)
oContentType = (new ContentType).@New("text/html; charset=utf-8")
? nl + "3. text/html; charset=utf-8 -> media type: " + oContentType.MediaType + ", charset: " + oContentType.CharSet
oSplit = (new AspMediaTypeHeaderValue).Parse("application/json; charset=utf-8; q=0.9")
? " with the headers library: type " + oSplit.Type.toString() + ", subtype " + oSplit.SubType.toString() + ", quality " + oSplit.Quality
# 4. The Accept header lists what the client understands, with a QUALITY (q) from 0 to 1 for each: the higher, the better. */* means
# "anything"; text/* means "any text type". The default quality is 1.
cAccept = "text/html, application/json;q=0.9, text/*;q=0.5, */*;q=0.1"
? nl + "4. the client sends: Accept: " + cAccept
aClient = parseAccept(cAccept)
for aItem in aClient
? " " + padRight(aItem[1],20) + "quality " + aItem[2]
next
# 5. Content negotiation: the server offers some types and sends the one that the client likes best
? nl + "5. what the server sends:"
for aOffer in [ ["application/json","text/csv"], ["text/csv","text/plain"], ["image/png"], ["text/html","application/json"] ]
? " offers " + padRight(joinList(aOffer),28) + "-> " + negotiate(aClient,aOffer)
next
# 6. A client that wants a JSON answer: Accept: application/json only. If the server has no JSON, the right answer is the status
# 406 Not Acceptable, not a guess.
aStrict = parseAccept("application/json")
? nl + "6. Accept: application/json, the server offers text/csv: " + negotiate(aStrict,["text/csv"])
func contentTypeOf oProvider,cFile
aResult = oProvider.TryGetContentType(cFile)
if aResult[1]
return aResult[2]
ok
return "application/octet-stream (not known)"
# the Accept header as a list of [type, quality], the best first (the sort is stable: types with the same quality keep their order)
func parseAccept cAccept
aItems = []
aParts = str2list(substr(cAccept,",",nl))
for cPart in aParts
oValue = (new AspMediaTypeHeaderValue).Parse(trim(cPart))
nQuality = oValue.Quality
if isObject(nQuality)
nQuality = 1 # no q parameter: quality 1
ok
aItems + [ oValue.MediaType.toString(), nQuality ]
next
nCount = len(aItems)
for i = 1 to nCount - 1
for j = 1 to nCount - i
if aItems[j][2] < aItems[j + 1][2]
aTemp = aItems[j]
aItems[j] = aItems[j + 1]
aItems[j + 1] = aTemp
ok
next
next
return aItems
# does the pattern of the Accept header (text/html, text/*, */*) cover the type?
func covers cPattern,cType
if cPattern = "*/*" or cPattern = cType
return True
ok
nSlash = substr(cPattern,"/")
return right(cPattern,2) = "/*" and left(cType,nSlash) = left(cPattern,nSlash)
# the offered type that the client likes best, or 406
func negotiate aClient,aOffers
for aItem in aClient
if aItem[2] > 0
for cOffer in aOffers
if covers(aItem[1],cOffer)
return cOffer + " (matched " + aItem[1] + ", quality " + aItem[2] + ")"
ok
next
ok
next
return "406 Not Acceptable"
func joinList aList
cText = ""
for item in aList
if cText != ""
cText += ", "
ok
cText += "" + item
next
return cText
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))1. file name -> content type:
index.html text/html
logo.png image/png
photo.JPG image/jpeg
data.json application/json
report.pdf application/pdf
archive.zip application/x-zip-compressed
notes.txt text/plain
song.mp3 audio/mpeg
movie.mp4 video/mp4
style.css text/css
app.js text/javascript
unknown.xyz123 application/octet-stream (not known)
2. after adding .ring: text/x-ring
(a file with an unknown type is sent as application/octet-stream: 'some bytes, download them')
3. text/html; charset=utf-8 -> media type: text/html, charset: utf-8
with the headers library: type application, subtype json, quality 0.90
4. the client sends: Accept: text/html, application/json;q=0.9, text/*;q=0.5, */*;q=0.1
text/html quality 1
application/json quality 0.90
text/* quality 0.50
*/* quality 0.10
5. what the server sends:
offers application/json, text/csv -> application/json (matched application/json, quality 0.90)
offers text/csv, text/plain -> text/csv (matched text/*, quality 0.50)
offers image/png -> image/png (matched */*, quality 0.10)
offers text/html, application/json -> text/html (matched text/html, quality 1)
6. Accept: application/json, the server offers text/csv: 406 Not AcceptableThis program uses a few generic functions (dnNew, dnStatic) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Type and subtype#
A MIME type has the form type/subtype: the type is the family (text, image, audio, video, application) and the subtype the exact format (html, png, json). After a semicolon come parameters: text/html; charset=utf-8 says that the text is encoded in UTF-8 (the tutorial Unicode and encodings explains encodings). A server that sends the wrong type causes real problems: a browser that receives a script as text/plain does not run it, and one that receives a page as text/plain shows the source.
From a file name#
FileExtensionContentTypeProvider.TryGetContentType(name) answers [ found, type ] (the tutorial Network tools explains the out value) from the extension of the file name, ignoring case (photo.JPG is image/jpeg). The table is built into the library: it knows the usual web, office, audio and video formats, and the exact text for some extensions changes between versions (for example, JavaScript is text/javascript today and was application/javascript before), so a test must not depend on it. For an extension that is not in the table, the right default is application/octet-stream: some bytes — download them, do not show them. Never guess text/html.
Mappings is a dictionary you can extend: Add(".ring", "text/x-ring") teaches the provider a type of your own. Do this once, at the start of the program.
The extension is what the name says, not what the content is. A file called photo.jpg can hold anything. For files that users upload, do not trust the type that comes with them: check the first bytes of the file (the magic numbers, the tutorial Binary files) and send downloads with Content-Disposition: attachment and the header X-Content-Type-Options: nosniff.
Reading Content-Type#
System.Net.Mime.ContentType parses a header into MediaType and CharSet; the headers library MediaTypeHeaderValue.Parse gives Type, SubType, Quality and the parameters. Their Type and SubType are small structs (StringSegment) that are turned into text with toString().
Accept and quality#
The client's Accept header lists the types it understands, separated by commas, each with an optional quality q from 0 to 1 (1 is the default; higher is better, and 0 means never). */* means anything and text/* any text type. The program parses the header, gives each item its quality, and sorts them best first (a simple, stable sort, so types with the same quality keep their order: the client's order breaks ties).
Content negotiation#
The server offers some types, and the best answer is the offered type that the client likes most: for each type of the Accept list, from best to worst, take the first offer that it covers. In step 5, a client that sends text/html, application/json;q=0.9, text/*;q=0.5, */*;q=0.1 gets application/json when the server offers JSON and CSV, gets text/csv when it offers CSV and plain text (matched by text/*), and gets a PNG only through */*. If nothing fits — a client that accepts only JSON and a server that has only CSV — the correct answer is 406 Not Acceptable, so that the client sees at once that the types do not agree, instead of receiving data it cannot use.
In real programs the negotiation also looks at the language (Accept-Language) and the encoding (Accept-Encoding: gzip, br, the tutorial Compression), with the same quality rules.
What you learned#
type/subtypeand parameters such ascharset,TryGetContentType, the defaultapplication/octet-stream, and your ownMappings,- the extension is not the content,
- the
Acceptlist, quality and wildcards, - negotiation and 406 Not Acceptable.
Exercises#
- Make the web server of the tutorial A tiny web framework send the right
Content-Typefor the files of a folder. - Parse
Accept-Language: ar, en;q=0.8, fr;q=0.5with the same functions and choose a language from the list of the languages you have. - Write
isAllowedUpload(name)that accepts onlyimage/png,image/jpegandapplication/pdf. - Add
*/*;q=0to an Accept header and see how it changes the answer.