在网络中为 PUT 请求绑定模型之前验证参数 api
Validate parameters before model binding for PUT request in web api
对于 PUT 请求的参数绑定,如何区分作为 String.Empty 发送的参数和根本不发送的参数。
我的请求 class 看起来像:
public class Person
{
string name {get; set;}
int? age {get; set;}
}
我的问题是绑定
当我的用户以
发送请求时
{
"name":"ABC"
}
在上述情况下年龄参数映射为空
但是,当请求如下所示时,它也会映射到 null。我想在以下情况下抛出验证错误。
我如何在 asp net core web api
中实现它
{
"name":"ABC",
"age":""
}
你应该看看 DataAnnotations。
您可以在可为 null 的 int 上添加 Range
属性。这将只允许整数或 null,而不是空字符串。
public class Person
{
string name {get; set;}
[Range(0,300)]
int? age {get; set;}
}
如果数据注释没有填满,它会将模型状态设置为 false
然后检查控制器方法中的模型状态
if (ModelState.IsValid)
{
// your logic
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
对于 PUT 请求的参数绑定,如何区分作为 String.Empty 发送的参数和根本不发送的参数。 我的请求 class 看起来像:
public class Person
{
string name {get; set;}
int? age {get; set;}
}
我的问题是绑定 当我的用户以
发送请求时{
"name":"ABC"
}
在上述情况下年龄参数映射为空 但是,当请求如下所示时,它也会映射到 null。我想在以下情况下抛出验证错误。 我如何在 asp net core web api
中实现它{
"name":"ABC",
"age":""
}
你应该看看 DataAnnotations。
您可以在可为 null 的 int 上添加 Range
属性。这将只允许整数或 null,而不是空字符串。
public class Person
{
string name {get; set;}
[Range(0,300)]
int? age {get; set;}
}
如果数据注释没有填满,它会将模型状态设置为 false
然后检查控制器方法中的模型状态
if (ModelState.IsValid)
{
// your logic
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}