'How to configure .NET Core API to always return JSON
I've created a .NET Core API. If I set the endpoint to return an object, it currently successfully returns it in JSON as desired. If the return type of the endpoint is void, however, it gives a 200 response, but the response header is text/html instead of application/json.
How can I configure my .NET Core API to always give a response with a JSON header?
Solution 1:[1]
You need to return JsonResult type, like
// GET: api/authors
[HttpGet]
public JsonResult Get()
{
return Json(_authorRepository.List());
}
Solution 2:[2]
add a filter of type ProducesAttribute("application/json") to the ConfigureServices. In the Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new ProducesAttribute("application/json"));
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serg.ID |
| Solution 2 | Sandeman |
