2017-01-11 29 views
7

我與郵差對.NET核心的WebAPI,無法投遞與郵遞員,錯誤數據 - 415不支持的MediaType

未知的媒體類型的錯誤發生測試我的第一個.NET核心的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); 
} 
+1

你可以發佈什麼的「標題」選項卡?嘗試將Content-Type設置爲application/json – Dealdiane

回答

18

你不發送Content-Type頭。選擇在鼠標指針附近的下拉JSON (application/json)你的第一個截圖: Like this

+0

感謝您的答案,但我在路由中使用了api。 –

0

這爲我工作(我使用的路線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