【问题标题】:.Net Core WebAPI , Unable to post data with POSTMAN , error - 415 Unsupported MediaType.Net Core WebAPI,无法使用 POSTMAN 发布数据,错误 - 415 Unsupported MediaType
【发布时间】:2017-05-26 15:10:28
【问题描述】:

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

发生未知媒体类型错误。

我错过了什么?

这是我的发帖对象

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

【问题讨论】:

  • 您可以发布“标题”选项卡中的内容吗?尝试将 Content-Type 设置为 application/json

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


【解决方案1】:

您没有发送 Content-Type 标头。在第一个屏幕截图中鼠标指针附近的下拉列表中选择 JSON (application/json)

【讨论】:

  • 感谢您的回答,但我在路由中使用了api。
  • 对于其他正在努力解决这个问题的人,违反直觉,而不是指定内容类型,然后提供表单数据,您需要选择原始数据。此时会出现新的编码类型下拉列表,您可以选择 JSON。恕我直言,糟糕的用户界面设计,但一旦你知道,你就知道了。
【解决方案2】:

这对我有用(我在路由中使用 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);
    }
}

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2023-03-24
    • 1970-01-01
    • 2019-08-22
    • 2015-09-12
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多