[英]C# ASP.NET MVC : how do I limit the number of characters passed in through a POST request?
I am using .cshtml
to send a POST
request to my controller. The following is my .cshtml
form.我正在使用
.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>
}
The number entered by the user will be sent to the controller as shown below:用户输入的号码会发送到controller,如下图:
[HttpPost]
public ActionResult PostTest(int test)
{
// process the data here
}
I am only expecting about 5 digits for the number that is passed in. However, if I enter a very large value with like 100 digits, the program crashes because I am using int
data type.对于传入的数字,我只期望大约 5 位数字。但是,如果我输入一个非常大的值,如 100 位数字,程序会崩溃,因为我使用的是
int
数据类型。 Even if I change to long
data type, this problem still occurs if I enter a large number.即使我改成
long
数据类型,输入大数还是会出现这个问题。 I think the program crashes when the argument was passed in way beyond its limit.我认为当参数以超出其限制的方式传递时程序会崩溃。
I did set a range to limit the data passed in from 0 to 99999. However, I want to prevent such a scenario in my controller action too.我确实设置了一个范围来限制从 0 到 99999 传入的数据。但是,我也想在我的 controller 操作中防止这种情况。 Is that possible?
那可能吗?
How do I solve this issue?我该如何解决这个问题?
You can use string instead of int.您可以使用字符串而不是 int。 Then
check if it convert into a int
and if it is in the desired range
.然后
check if it convert into a int
以及它is in the desired range
。 try this:试试这个:
[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 ... ");
}
You can create a request data object and in this creating use Fluent Validation for this field it will give you an error after that you can send after this error BadRequest.您可以创建一个请求数据 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.