簡體   English   中英

將 json 發布到我的 web-api 的問題。 我該如何解決

[英]Problem with posting json to my web-api. How can i solve it

我是 web api 的新手,現在使用 .net 3 制作一個簡單的程序在我的控制器中,我創建了簡單的 post 方法

[HttpPost]
public ActionResult Post(CountryPostRequest countryPostRequest)
{
    var savedCity = new City {Name=countryPostRequest.Capital};
    var savedRegion = countryDb.Regions.Add(new Region { Name = countryPostRequest.Region });
    var savedCountry = countryDb.Countries.Add(new Countrie { Name = countryPostRequest.Name, Region = new Region { Name = countryPostRequest.Region }, Capital = savedCity, AreaSize = countryPostRequest.AreaSize, CountryCode = countryPostRequest.CountryCode, Population = countryPostRequest.Population });
    countryDb.SaveChanges();
    return RedirectToAction(nameof(Get));
}

此方法獲取 CountryPostRequest。 它看起來像那樣

public class CountryPostRequest
{
    public string Name { set; get; }
    public string CountryCode { set; get; }
    public int Population { set; get; }
    public double AreaSize { set; get; }
    public string Capital { set; get; }
    public string Region { set; get; }
}

總的來說,我嘗試使用郵遞員發布此原始文件

{
   "Name" : "Roman Empire",
   "CountryCode" : "RE",
   "Population" : 22,
   "AreaSize": 22.0,
   "Capital" : "Rome",
   "Region" : "EU"
}

郵遞員給我一個結果:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "|db653ff6-46b8be8826b56364."
}

獲取方法工作正常。 什么不正確? 請幫忙

專門針對您的情況,因為您使用postman來調用您的 API:

您需要將 postman 中的內容類型設置為 JSON (application/json)。 轉到 POST 請求中的正文,您會在那里找到原始選項。 在它旁邊,會有一個下拉菜單,選擇 JSON。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM