I'm writing a ASP.NET Web API 2 project. I've created a request model that contains properties that will be the input to my API. For GET requests, I enumerate the properties in the method's parameter list, and for POST request, I have the Request object as the sole parameter.
How can I specify optional properties in my Request object? I would like to specify "Count" as an optional parameter of the request model. Would this do the trick?
For POST methods:
class Request{
public int id {get;set;}
public int? Count{get;set;}
}
For GET methods:
public Response MyActionMethod(int id, int? Count)
Haven't you tried it yourself, before posting the question?
Yes, this would do the trick. More proper examples:
[HttpPost]
virtual object Foo([FromBody] Request req);
// query parameters (as object)
[HttpGet]
virtual object Foo([FromUri] Request req);
// query parameters (as arguments)
[HttpGet]
virtual object Foo(int id, int? count = null);
//uri + query parameters
[HttpGet]
[Route('/path/:id')]
virtual object Foo(int id, int? count = null);
Instead of int?
you can just use int
, then 0
is the default value in Object Request
, and for the method arguments, you should set the default value yourself int count = 0
.
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.