简体   繁体   中英

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.

@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:

[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. Even if I change to long data type, this problem still occurs if I enter a large number. 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. Is that possible?

How do I solve this issue?

You can use string instead of int. Then check if it convert into a int and if it 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.

public class MyTest {
    [Range(0, 2147483646)]
    public int myproperty {get;set;}
}



    [HttpPost]
    public ActionResult PostTest(MyTest test) 
    {
         // process the data here
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM