Chief
Chief

Reputation: 963

.Net Core 5 Post Response returns Incorrect Content-Type: application/json

Using .Net Core 5, I have configured my application with the necessary packages needed to make work of application/json.

Using the [FromBody] parameter attribute, and posting the data using postman results in the following error:

Incorrect Content-Type: application/json

I have already configured the AddControllers(...) method in startup with the .AddNewtonsoftJson(...).

services.AddControllers(options =>
        {
            options.Filters.Add(new ProducesAttribute("application/json"));
            options.RespectBrowserAcceptHeader = true; // false by default
        }).AddNewtonsoftJson(options =>
       options.SerializerSettings.ContractResolver =
          new CamelCasePropertyNamesContractResolver());

Below is the code from the controller

public async Task<IActionResult> Post([FromBody] ProjectRequest pr)
    {
        try
        {
            var proj = new Project
            {
                Id = Guid.NewGuid().ToString(),
                Name = pr.Name,
                Excerpt = pr.Excerpt,
                Tags = pr.Tags
            };

            var resp = new
            {
                Data = "Project Added successfully"
            };

            return Ok(resp);

        } catch(Exception e)
        {
            var br = new
            {
                Data = $"An error occured : {e.Message}"
            };

            return BadRequest(br);
        }
    }

I cannot figure out why this error is still being thrown.

Upvotes: 2

Views: 1531

Answers (1)

Tupac
Tupac

Reputation: 2910

Are you correct to post the data with postman, my example can work normally:

Postman: enter image description here

Controller: After sending the data, then the controller receives the data

enter image description here

Finally received the value

 {
     "data": "Project Added successfully"
}

enter image description here

Upvotes: 2

Related Questions