我还在学习网络API,所以请原谅我,如果我的问题听起来很愚蠢.
我有这个StudentController:
public HttpResponseMessage PostStudent([FromBody]Models.Student student)
{
if (DBManager.createStudent(student) != null)
return Request.CreateResponse(HttpStatusCode.Created, student);
else
return Request.CreateResponse(HttpStatusCode.BadRequest, student);
}
Run Code Online (Sandbox Code Playgroud)
为了测试这是否有效,我使用Google Chrome的扩展程序"Postman"来构建HTTP POST请求以对其进行测试.
这是我的原始POST请求:
POST /api/Student HTTP/1.1
Host: localhost:1118
Content-Type: application/json
Cache-Control: no-cache
{"student": [{"name":"John Doe", "age":18, "country":"United States of America"}]}
Run Code Online (Sandbox Code Playgroud)
"student"应该是一个对象,但是当我调试应用程序时,API接收学生对象,但内容始终是NULL.
我创建了一个ASP.net Web API控制器:
public class UsersController : ApiController
{
//...
public void Put([FromBody]User_API user, long UpdateTicks)
{
user.UpdateTicks = UpdateTicks;
//...
}
}
Run Code Online (Sandbox Code Playgroud)
如果客户端未提供正确的参数,则"user"参数将为null.我可以创建一个全局过滤器来检查这样的每个参数,如果发生任何错误,将返回400消息.
是否可以在不使用模型的情况下验证操作的查询参数?我的API中的许多调用都是一次性的,如果只使用一次,我看不出为它们建立模型的意义。
我看了下面的文章,看起来好像正是我所需要的,只是我不希望它在不存在所需的parm的情况下返回404,我希望它返回类似于已烘焙的错误消息的对象在模型验证中-实际上,我只是希望将参数像模型一样对待,而无需实际创建模型。
https://www.strathweb.com/2016/09/required-query-string-parameters-in-asp-net-core-mvc/
[HttpPost]
public async Task<IActionResult> Post(
[FromQueryRequired] int? Id,
[FromQuery] string Company)
Run Code Online (Sandbox Code Playgroud)
编辑:
[FromQueryRequired]是一个自定义ActionConstraint,如果缺少ID parm,则抛出404(这直接从文章中获取)。但是,我不需要404,我想要一个对象,该对象的信息为{MESSAGE:“ ID is required”“}。我认为问题是我无法从操作约束中访问Response上下文。