Given this method in a Controller
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
A request like this is successful! http://localhost:53351/api/values/ abc
Why?
IMHO, this should throw as a Bad Request because the id is not a number (it's "abc"). Instead, I'm getting a 0 (zero) as the id
parameter.
MOREOVER =>
A very similar problem also happens in methods like this:
[HttpGet("{id}")]
public string Get(int id, [FromQuery]QueryObject queryObj)
{
return "value";
}
public class QueryObject
{
public int Number { get; set; }
public string String { get; set; }
}
In a request like this http://localhost:53351/api/values/1?String=hello&Number= abc the object that is parsed and put as queryObj
will come with its number property set to 0 (zero).
This makes invalid data go through the pipe! Can we avoid this behavior?
You can restrict the type of the parameter like this:
[HttpGet("{id:int}")]
From docs
Second Part
You need to add [FromQuery]
attribute to the model properties
public class QueryObject
{
[FromQuery(Name = "Number")]
public int Number { get; set; }
[FromQuery(Name = "String")]
public string String { get; set; }
}
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.