c# - 将 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."
}
获取方法工作正常。有什么不正确的?请帮忙
解决方案
专门针对您的情况,因为您使用postman
的是调用 API:
您需要将 postman 中的内容类型设置为 JSON (application/json)。转到您的 POST 请求中的正文,在那里您将找到原始选项。在它旁边会有一个下拉菜单,选择 JSON。
推荐阅读
- angular - 在甜甜圈图中调用 fontSize 函数(打字稿)
- php - 如果保存在 id laravel 中,如何在下拉列表中选择多个项目?
- python - 用mechanicalsoup下载文件
- c - “在C程序中,如何取一个(char数组),即用户输入的字符串(包括空格),其长度也应该是用户输入的值?
- haskell - 试图用 SBV 解决祖先关系的约束
- angular - 为什么我在传单弹出窗口中的按钮不起作用?
- c# - 如何将 XAML 文件中 LayoutAnchorableItem 的 Style 属性与 AvalonDock 绑定?
- c++ - 如何查看结构、类对象的内存布局
- api - POSTMAN - 测试失败假为真
- sql - ORACLE:在第 1 列中选择 de MAX 值后,在第 2 列中选择 de MAX 值