136

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
  • 24,161
  • 21
  • 159
  • 240
Maxim Eliseev
  • 3,248
  • 4
  • 29
  • 35
  • 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

193

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
  • 2,224
  • 2
  • 14
  • 11
71

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,932
  • 3
  • 45
  • 72
Kevin
  • 1,934
  • 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
  • 56
    .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
6

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,527
  • 4
  • 52
  • 67