.Net Core WebAPI,无法使用POSTMAN发布数据,错误 - 415不支持的MediaType

时间:2017-01-11 17:48:47

标签: rest asp.net-web-api2 asp.net-core-mvc postman

我正在使用Postman测试我的第一个.net Core WebAPI

  

发生了未知的媒体类型错误。

我错过了什么?

This is postman rest client

这是我的发布对象

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

这是webapi控制器

[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);
}

2 个答案:

答案 0 :(得分:27)

您未发送#include <sstream> #include <string> std::string leaderBoard; std::stringstream sstream; for (unsigned contor = 0; contor < myPlayer->getPlayerRoom()->playersInRoom.size(); ++contor) { sstream << myPlayer->getPlayerRoom()->playersInRoom.at(contor)->getPlayerName(); sstream << "-----"; sstream << to_string(myPlayer->getPlayerRoom()->playersInRoom.at(contor)->getPlayerScore()); sstream << '\n'; } leaderBoard = sstream.str(); 标头。在第一个屏幕截图中的鼠标指针旁边的下拉列表中选择Content-TypeLike this

答案 1 :(得分:1)

这对我有用(我在路线中使用了api)

[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