问题
Previously in WebAPI (beta) I was able to create a "GetAll" method that took in optional parameters added on the URI:
http://localhost/api/product?take=5&skip=10
This still seems to work but only if I include all the parameters. In (beta), I could omit the parameters ( http://localhost/api/product/ ) and the "GetAll" method would get called (take & skip would be null). I could also omit some of the parameters http://localhost/api/product?take=5 (skip would be null)
public IEnumerable<ProductHeaderDto> GetAll(int? take, int? skip)
{
var results = from p in productRepository
select new ProductHeaderDto
{
Id = p.Id,
Version = p.Version,
Code = p.Code,
Description = p.DescriptionInternal,
DisplayName = p.Code + " " + p.DescriptionInternal
};
if (skip != null) results = results.Skip(skip.Value);
if (take != null) results = results.Take(take.Value);
return results;
}
In (RC), I now get "No action was found on the controller 'Product' that matches the request." when both or one of the parameters are missing. I have tried adding [FromUri] on the method parameters but that has no affect:
public IEnumerable<ProductHeaderDto> GetAll([FromUri] int? take, [FromUri] int? skip)
I have also tried setting default values:
public IEnumerable<ProductHeaderDto> GetAll(int? take = null, int? skip = null)
Is there some sort of "optional" parameter attribute that could be used when trying to match the method signature?
回答1:
This is a bug which has been fixed in RTM. You can have optional parameter by specifying default value.
public IEnumerable<string> Get(int? take = null, int? skip = null)
BTW, you can use $skip and $top in web api odata package to achieve the same functions.
来源:https://stackoverflow.com/questions/11640639/webapi-rc-getall-with-uri-parameters