1. Pay attention to the post-type api in .net core (the premise is that the [ApiController] feature is added to the Controller). The default is this.
1. If the client Content-Type is application/json, if the api interface uses a single object as a parameter, the parameter can be parsed normally with or without adding [FromBody], but if the object list is used as a parameter, it must be added [FromBody], otherwise [FromBody] must be added, otherwise the parameters cannot be read.
2. If the client's Content-Type is not application/json, the api interface must add [FromForm], otherwise the client will report a 400 error when calling the interface.
3. If [FromBody] is added and the Content-Type of the client is not application/json, the interface will report a 400 error.
How does asp.net core webapi receive Josn and convert it into an entity
Now you can treat JSON as a parameter such as data = "JSON" and serialize it after receiving it. Is there an asynchronous method for receiving automatic conversion before :
code show as below:
/// <summary>
/// 站点信息
/// </summary>
/// <param name="SStation">站点编码</param>
/// <param name="Type">站点类型:地表水:Dbs 引用水:yys 空气:Air 自动站:waterzd 酸雨:rain</param>
/// <returns></returns>
[HttpGet, HttpPost]
[AllowAnonymous]
public ActionResult SStationInfo([FromForm] string SStation, [FromForm] string Type)
{
string message = string.Empty;
if (string.IsNullOrEmpty(SStation)) {
message = $"缺少[SStation]参数!";
return Ok(new { code = 201, message });
}
if (string.IsNullOrEmpty(Type))
{
message = $"缺少[Type]参数!";
return Ok(new { code = 201, message });
}
StnDetail stnDetail = new StnDetail();
stnDetail.imgs = this.Dao.FindAll<SStationImg>().Where(p => p.SStation == SStation).ToList();
switch (Type)
{
case "Air":
stnDetail.air= this.Dao.FindAll<Air_SStation>().Where(p => p.SStation==SStation).FirstOrDefault();
break;
case "Dbs":
stnDetail.dbs = this.Dao.FindAll<Dbs_SStation>().Where(p => p.SStation == SStation).FirstOrDefault();
break;
case "yys":
stnDetail.dws = this.Dao.FindAll<DrinkingWater_SStation>().Where(p => p.SStation == SStation).FirstOrDefault();
break;
case "rain":
stnDetail.rs = this.Dao.FindAll<Rain_SStation>().Where(p => p.SStationCode == SStation).FirstOrDefault();
break;
case "waterzd":
stnDetail.ws = this.Dao.FindAll<WaterZd_SStation>().Where(p => p.SStation == SStation).FirstOrDefault();
break;
default:
message = $"[Type]参数错误!";
break;
}
return Ok(new { code = 200, message, stnDetail });
}
Based on the above, if the client submits json data, it is recommended to add [FromBody].
If the Content-Type of the data submitted by the client is not application/json, an error will be reported. To solve the error, you need to add [FromForm] to the interface.