首页 > 解决方案 > 将 json 发布到我的 web-api 时出现问题。我该如何解决

问题描述

我是 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."
}

获取方法工作正常。有什么不正确的?请帮忙

标签: c#jsonasp.net-corehttp-postasp.net-core-webapi

解决方案


专门针对您的情况,因为您使用postman的是调用 API:

您需要将 postman 中的内容类型设置为 JSON (application/json)。转到您的 POST 请求中的正文,在那里您将找到原始选项。在它旁边会有一个下拉菜单,选择 JSON。


推荐阅读