95

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
  • 18,275
  • 13
  • 127
  • 181
Maxim Eliseev
  • 2,630
  • 2
  • 25
  • 33
  • 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

2 Answers2

100

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,297
  • 1
  • 9
  • 11
64

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,025
  • 3
  • 39
  • 60
Kevin
  • 1,742
  • 1
  • 14
  • 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
  • 46
    .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