"application/json" constant in .NET framework

C#.Netasp.net MvcContent Type

C# Problem Overview


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"?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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

System.Net.Mime.MediaTypeNames.Application.Json

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaxim EliseevView Question on Stackoverflow
Solution 1 - C#Bob Van de VijverView Answer on Stackoverflow
Solution 2 - C#KevinView Answer on Stackoverflow
Solution 3 - C#MickView Answer on Stackoverflow