Sanwar Ranwa
How to make sure that Web API returns data in JSON format only?
By Sanwar Ranwa in .NET Core on Jul 18 2018
  • Uzma Khan
    Oct, 2018 1

    In WebApiConfig.cs file in solution add mentioned line as shown in examplepublic static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); //To produce JSON format add this line of code config.Formatters.JsonFormatter.SupportedMediaTypes.Add(newMediaTypeHeaderValue("text/html")); }

    • 3
  • Vladimir Lapenkov
    Feb, 2019 6

    [Produces("application/json")]

    • 2
  • Bhagawat Shinde
    Jul, 2023 16

    To ensure that a Web API always returns data in JSON format, you can apply the following steps:

    Configure JSON as the default content type: In the ConfigureServices method of your Startup class, add the following code to configure JSON as the default content type for your Web API:

    1. services.AddControllers().AddJsonOptions(options =>;;
    2. {
    3. options.JsonSerializerOptions.PropertyNamingPolicy = null;
    4. });`

    This configures the JsonOptions to use the default JSON serializer and disables the property naming policy, allowing the JSON output to match your object’s property names exactly.

    Set the response type explicitly: In your Web API controller methods, you can use the [Produces] attribute to specify that the response should always be in JSON format. Add the following code to the top of your controller class or individual action methods:

    1. [Produces("application/json")]

    By specifying “application/json” as the response type, it ensures that the Web API will return data in JSON format regardless of the client’s request headers.

    Configure content negotiation: Optionally, you can configure content negotiation in your Startup class to handle client requests that explicitly specify a different content type. In the ConfigureServices method, add the following code:

    services.AddControllers()

    1. .AddMvcOptions(options =>;;
    2. {
    3. options.RespectBrowserAcceptHeader = true;
    4. options.ReturnHttpNotAcceptable = true;
    5. });

    With this configuration, if a client sends a request with an Accept header specifying a content type other than JSON, the Web API will return a 406 Not Acceptable status code.

    By following these steps, you ensure that your Web API always returns data in JSON format, both by default and when explicitly requested by the client.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS