c# - 在 C# 的控制器中读取 POST 请求的请求正文
问题描述
我正在对 API 实现进行原型设计,但遇到了一个基本问题,即无法读取JSON
我在请求正文中传递的对象Fiddler
。我的实现基于我在不同初学者教程中找到的一些示例。
这是我对 API 的调用:
https://{Something}/servername/{something1}/checkAvailability?{api-version}
这是一个POST请求,请求正文是(JSON):{name:"resource1", option:"include"}
我试图在控制器上解析它的方式是使用 [FromBody]。但是,[FromBody] 参数始终被读取为 null:
[HttpPost]
// A bunch of other attributes.
public HttpResponseMessage CheckAvailability(
string serverName,
[FromBody] CheckProperties props)
{
// While debugging, I am able to reach here and successfully see the serverName as "something1" which passed in the API
if (serverName == null || serverName == "")
{
return CreateResponse(HttpStatusCode.BadRequest);
}
// Able to reach here but the value of props is read as null. What is the right way to read the request body in props(CheckNameProperties) object?
if (props != null) // props is always null for me.
{
// Do something
}
}
检查属性.cs
public class CheckProperties
{
[JsonProperty]
public string Name{ get; set; }
[JsonProperty]
public string Option { get; set; }
public CheckProperties(string name, string options)
{
Name = name;
Option = options;
}
}
我没有使用对象,而是尝试读取一个简单的字符串。但是,也读不出来。
此外,如果有人可以分享帮助他们对实现 API 有很好的基本了解的教程,那就太好了。我遇到的大多数教程都在讨论 API 设计原则,而不是实现它的方法。
解决方案
推荐阅读
- c# - VM解析成本高吗?MVVM Autofac
- mysql - MySQL 存储过程插入循环
- java - 使用 Streams 的嵌套 EnumMap
- java - 完成处理队列时停止线程的最佳实践
- python - 如何从运行在 IBM i 上的 Python 连接到 Oracle?
- sql - SQL - 选择具有不同组 ID 的用户对
- python - 为 tabWidget Python 导入负责的小部件页面
- java - 如何从番石榴重试器获取原始错误消息?
- python - Sklearn分类与DecisionTree,如何提高拟合?
- sql-server - 使用 sql repoting servives 创建多页、类似模板的报告