114

I've just declared a constant for the "application/json" content type in one of my classes.

public const string JsonContentType = "application/json";

I'm not sure it is a good practice.

Does .NET framework have a predefined const for "application/json"?

RBT
  • 21,293
  • 19
  • 144
  • 210
Maxim Eliseev
  • 2,888
  • 3
  • 27
  • 34
  • 2
    See http://stackoverflow.com/questions/1015892/is-there-an-enum-for-the-contenttype-property-on-a-httpwebresponse-text-plain – Andreas Adler Dec 18 '13 at 10:46
  • Related post - [ASP MVC - Are there any constants for the default content types?](https://stackoverflow.com/q/10362140/465053) & [What is the correct JSON content type?](https://stackoverflow.com/q/477816/465053) – RBT Feb 28 '19 at 04:57

3 Answers3

153

In order to add an up-to-date answer: since dotnet core 2.1 MediaTypeNames.Application.Json has been defined.

See https://github.com/dotnet/corefx/pull/26701 for the changeset.

Bob Van de Vijver
  • 1,827
  • 2
  • 12
  • 11
66

See Newer Answer. This answer is now inaccurate.

While there are some MIME constants defined in MediaTypeNames (see here), there no constant for "application/json".

Putting additional content types in a shared const is probably best practice, better than defining them in string literals a million times throughout your code at least.

Plus it gives you the flexibility of using new/custom MIME types, which a specific .NET version might not have.

Andy Joiner
  • 5,405
  • 3
  • 41
  • 67
Kevin
  • 1,812
  • 1
  • 15
  • 10
  • Glad that you mentioned about defining a public const best practice. That's the #cleanCode way of doing it rather than littering your code here and there. – RBT Jan 09 '17 at 06:44
  • The implied conclusion that it "enables" new/custom MIME types does not hold as having a *string constant* defined does not preclude additions to the open set (all possible strings) accepted. Since JSON/XML/HTML are so ubiquitous on the internet, having these standard (in one of the several) .NET Net/Web assemblies would be useful.. I wonder if .NET Core changes this answer? – user2864740 Jun 12 '18 at 19:34
  • Arg, or, with the related answer.. if only "application/json" was added.. – user2864740 Jun 12 '18 at 20:07
  • 54
    .NET Core 2.1.0 has the `MediaTypeNames.Application.Json` defined :) See https://github.com/dotnet/corefx/pull/26701. – Bob Van de Vijver Feb 12 '19 at 13:02
1

There is now for Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6...

System.Net.Mime.MediaTypeNames.Application.Json

Mick
  • 6,170
  • 4
  • 47
  • 63