Pregunta

I recently found the handy method .several() in Restangular. Which allows me to fetch multiple single objects, very nice.

So I tried it out the following Restangular.several('accounts', 'a', 'b', 'c'); which generates this url: /api/accounts/a,b,c

Which doesn't sit very well with my ASP.NET Web Api controller. First draft:

public class MyController : ApiController
{
    public HttpResponseMessage GetAll() { ... }
    public HttpResponseMessage GetSingle(string id) { ... }
    public HttpResponseMessage GetMultiple(IEnumerable<string> ids) { ... }
}

This would be the ideal controller from my perspective. However it fails with an exception saying that MVC can't distinguish between the actinos :(

Second draft:

public class MyController : ApiController
{
    public HttpResponseMessage GetAll() { ... }
    public HttpResponseMessage GetSingle(string id) { ... }
}

Now this doesn't crash. But id is a,b,c.

Do I really need to manually split the string and work with it from there? Also this wont work for int types. public HttpResponseMessage GetSingle(int id) { ... }

What is the proper way to implement .several() support in ASP.NET Web Api? I assume it's a standard REST call since it's in Restangular.

¿Fue útil?

Solución

Attribute Routing with regex constraints can work here...

[Route("api/my")]
public HttpResponseMessage GetAll() {
    // ...
}

[Route("api/my/{id:regex(^[^,]+$)}")]
public HttpResponseMessage GetSingle(string id)
{
    // ...
}

[Route("api/my/{ids:regex(,)}")]
public HttpResponseMessage GetMultiple(string ids)
{
    // strings
    var idList = ids.Split(',');

    //// ints
    // var idList = ids.Split(',').Select(i => Convert.ToInt32(i)).ToList();

    // ...
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top