asp.net parses wrong numeric values as 0

时间:2018-05-28 18:43:49

标签: c# asp.net .net-core asp.net-core-2.0 asp.net-core-webapi

When passing a wrong or empty value to a numeric parameter it gets parsed as 0. e.g. if you call something like this -> /api/getValue?id=abc

and id is an int, id will have a 0 value instead of throwing an exception.

The same would happen if the call had an empty value -> /api/getValue?id=

 

Any way to make this error throw an exception instead of it passing the wrong value to the method?

BTW, using a nullable int makes you unable to use a parameterless overload so it isn't a solution.

2 个答案:

答案 0 :(得分:1)

Use the following method:

int my_query;
if (!string.IsNullOrEmpty(Request.QueryString["id"]) && int.TryParse(Request.QueryString["id"], out my_query))
{
// do something!
}

Hope it helps.

答案 1 :(得分:1)

Try this:

[HttpGet("{id}")]
public IActionResult Get(int id)
{
     if(!ModelState.IsValid)
     {
         return BadRequest();
     }
     return Ok();
}

The ModelState.IsValid will be false if a non numeric value has passed as parameter. You can throw an Exception inside the if-statement if you wish.