[英]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.