Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core WebAPI , Unable to post data with POSTMAN , error - 415 Unsupported MediaType

I am testing my first .net Core WebAPI with Postman

unknown media type error is occurring.

What am I missing?

This is postman rest client

This is my posting object

public class Country
{
    [Key]
    public int CountryID { get; set; }
    public string CountryName { get; set; }
    public string CountryShortName { get; set; }
    public string Description { get; set; }
}

This is the webapi controller

[HttpPost]
public async Task<IActionResult> PostCountry([FromBody] Country country)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _context.Country.Add(country);
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (CountryExists(country.CountryID))
        {
            return new StatusCodeResult(StatusCodes.Status409Conflict);
        }
        else
        {
            throw;
        }
    }

    return CreatedAtAction("GetCountry", new { id = country.CountryID }, country);
}
like image 597
Arun Prasad E S Avatar asked Jan 11 '17 17:01

Arun Prasad E S


2 Answers

You're not sending the Content-Type header. Choose JSON (application/json) in the dropdown near the mouse pointer on your first screenshot: Like this

like image 142
Gebb Avatar answered Sep 19 '22 05:09

Gebb


This worked for me (I was using api in the route)

[Produces("application/json")]
[Route("api/Countries")]
public class CountriesController : Controller
{
    // POST: api/Countries
    [HttpPost]
    public async Task<IActionResult> PostCountry([FromBody] Country country)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Country.Add(country);
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (CountryExists(country.CountryID))
            {
                return new StatusCodeResult(StatusCodes.Status409Conflict);
            }
            else
            {
                throw;
            }
        }

        return CreatedAtAction("GetCountry", new { id = country.CountryID }, country);
    }
}

enter image description here

like image 24
Arun Prasad E S Avatar answered Sep 22 '22 05:09

Arun Prasad E S