C# webAPI 无法将原始整数值绑定到正文中的模型?
C# webAPI cannot bind original integer value to model from the body?
我的问题是当我将负载主体中以零 (012345) 开头的任何整数值发送到 C# web API 接收到的值没有第一个数字 (12345)。它忽略了零。如何强制API接收原始数据?
[HttpPost]
public void insertdata([FromBody]Model model)
{
// model.id=1234
}
有效载荷
{id:01234}
将任何整数值作为字符串“012345”发送 - 负载 {id:“01234”}。另一种方法是使用 string.PadLeft - model.Id.ToString(),PadLeft(5,"0");
我认为这取决于模型对象中 id 属性 的数据类型。
如果 id 是一个字符串,例如 01234 中的前导零将被保留。如果您的要求不是特别限制您将 id
属性 设为 int
public class Model
{
public string id { get; set;}
...
}
正如@Richard 在评论中提到的,整数不能有前导零
您应该在模型中使用字符串。
public class YourModel {
public string id {get;set;}
}
[HttpPost]
public void insertdata(YourModel model)
{
model.id="01234";
}
早上好伙计,
按照我在 POC 中做的例子,这样做有一些问题,当有人发送大于 5 的 id 时,可能会导致搜索错误或导致重复,理想的情况是他们以字符串格式发送.更重要的是,只要 id 在 5 个字符之间,这个解决方案就可以工作。
参考:
https://docs.microsoft.com/pt-br/dotnet/standard/base-types/custom-numeric-format-strings
我的问题是当我将负载主体中以零 (012345) 开头的任何整数值发送到 C# web API 接收到的值没有第一个数字 (12345)。它忽略了零。如何强制API接收原始数据?
[HttpPost]
public void insertdata([FromBody]Model model)
{
// model.id=1234
}
有效载荷
{id:01234}
将任何整数值作为字符串“012345”发送 - 负载 {id:“01234”}。另一种方法是使用 string.PadLeft - model.Id.ToString(),PadLeft(5,"0");
我认为这取决于模型对象中 id 属性 的数据类型。
如果 id 是一个字符串,例如 01234 中的前导零将被保留。如果您的要求不是特别限制您将 id
属性 设为 int
public class Model
{
public string id { get; set;}
...
}
正如@Richard 在评论中提到的,整数不能有前导零
您应该在模型中使用字符串。
public class YourModel {
public string id {get;set;}
}
[HttpPost]
public void insertdata(YourModel model)
{
model.id="01234";
}
早上好伙计,
按照我在 POC 中做的例子,这样做有一些问题,当有人发送大于 5 的 id 时,可能会导致搜索错误或导致重复,理想的情况是他们以字符串格式发送.更重要的是,只要 id 在 5 个字符之间,这个解决方案就可以工作。
参考:
https://docs.microsoft.com/pt-br/dotnet/standard/base-types/custom-numeric-format-strings