简体   繁体   中英

Is it possible to route to an action with params in Web API .net?

is it possible to route to action?

    [HttpGet]
    public List<Product> GET(int CategoryId, string option, params string[] properties)
    {
        List<Product> result = new List<Product>();
        result = BusinessRules.getProductsByCategoryId(CategoryId);
        return result;
    }

so that the URL would look like "/api/Products/CategoryId/full/Name/ProductID/"

It calls the action probably because properties is optional,but the properties parameter is always null. I even tried passing Name and ProductID arguments in the body of the request and still properties is null. I want to use "params" because I would like to pass 0..N arguements to the action.

Here is the route template.

    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{CategoryId}/{option}/{*properties}",
            constraints: new { CategoryId = @"\d+" },
            defaults: new { option = RouteParameter.Optional, properties = RouteParameter.Optional }
    );

Check out this post: http://www.tugberkugurlu.com/archive/asp-net-web-api-catch-all-route-parameter-binding

It goes through creating a custom parameter binding to convert any catch-all query params into an array. I like the idea of not registering it globally but using it to decorate where you'll need it, like so:

 public HttpResponseMessage Get([BindCatchAllRoute('/')]string[] tags) { ...

Of course, you can always use the regular query string. It is certainly easy:

[HttpGet]
public List<Product> GET(int CategoryId, string option, [FromUri] string[] properties = null)
{
    List<Product> result = new List<Product>();
    result = BusinessRules.getProductsByCategoryId(CategoryId);
    return result;
}

and call it like so: /api/Products/123/full/?properties=Name&properties=ProductID

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