[英]C# ASP.NET MVC : how do I limit the number of characters passed in through a POST request?
我正在使用.cshtml
向我的 controller 发送POST
请求。以下是我的.cshtml
表单。
@using (Html.BeginForm("PostTest, "Test", FormMethod.Post))
{
<input type="number" name="test" min="0" max="99999" />
<button type="submit">Submit</button>
}
用户输入的号码会发送到controller,如下图:
[HttpPost]
public ActionResult PostTest(int test)
{
// process the data here
}
对于传入的数字,我只期望大约 5 位数字。但是,如果我输入一个非常大的值,如 100 位数字,程序会崩溃,因为我使用的是int
数据类型。 即使我改成long
数据类型,输入大数还是会出现这个问题。 我认为当参数以超出其限制的方式传递时程序会崩溃。
我确实设置了一个范围来限制从 0 到 99999 传入的数据。但是,我也想在我的 controller 操作中防止这种情况。 那可能吗?
我该如何解决这个问题?
您可以使用字符串而不是 int。 然后check if it convert into a int
以及它is in the desired range
。 试试这个:
[HttpPost]
public ActionResult PostTest(string test)
{
int number = -1;
var result = int.TryParse(test, out number);
if (result && number >= 0 && number <= 99999)
return Ok(number);
else
return BadRequest("the number is in the wrong format ... ");
}
您可以创建一个请求数据 object,在此创建过程中对此字段使用 Fluent Validation,它会给您一个错误,之后您可以在此错误 BadRequest 之后发送。
public class MyTest {
[Range(0, 2147483646)]
public int myproperty {get;set;}
}
[HttpPost]
public ActionResult PostTest(MyTest test)
{
// process the data here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.