Tip - Use Constants For MIME Types
[C#, .NET, Tips]
Quick, what’s wrong with this code?
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("appliction/json"));
Took me longer than I am prepared to admit to notice that the reason my code was not working is that there is a typo there - it should read application/json and not appliction/json.
Wiring code like this exposes you to a number of problems.
- Typos!
- Since you are typing this string everywhere, should you need to change it, it will be a messy process.
- Subtle bugs can be introduces where in some scenarios the
stringis correct, but one or more letters has a different case.
The solution to this, naturally, is constants.
You might be tempted to do something like this:
const string ApplicationJSON = "application/json"
And then go on to use it like this:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApplicationJSON));
But there is no need. The solution already exists in the System.Net.Mime namespace.
The string application/json is accessed as the constant MediaTypeNames.Application.Json.
The same pattern will apply should we need the string text/csv.
This is accessible via the constant MediaTypeNames.Text.Csv .
The same applies to the other namespaces - Font, Image and Multipart, as well as the ones we have seen - Application and Text.
Our original code now will be as follows:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json));
TLDR
System.Net.Mime namespace contains a large number of constants that you can use for your HTTP coding.
Happy hacking!