vendredi 4 mai 2018

ASP .NET Web API route not found

I have a pretty basic ASP.Net Web API project with an ApiController class as follows (greatly simplified here, as the issue is the routing, not the action of the methods):

// A Controller for accessing data from ord.WarehouseFreight
[RoutePrefix("api/ordWarehouseFreight")]
public partial class ordWarehouseFreightController : ApiController
{
    // Get all values from ord.WarehouseFreight
    [Route("")]
    public IHttpActionResult Get()
    {
        List<ordWarehouseFreight> output = new List<ordWarehouseFreight>();
        return Ok(output);
    }

    // Return a single value from ord.WarehouseFreight using the primary key as ID.
    // <param name="id">The WarehouseFreight Primary Key.</param>
    [Route("{id:int}")]
    public IHttpActionResult Get(int id)
    {
        item = new ordWarehouseFreight();
        return Ok(item);
    }

    // Get selected values from the ord.WarehouseFreight
    // <param name="idList">A comma delimited list of ord.WarehouseFreight Primary Keys.</param>
    [Route("{idList}")]
    public IHttpActionResult Get(string idList)
    {
        List<ordWarehouseFreight> output = new List<ordWarehouseFreight>();
        return Ok(output);
    }
}

The relevant portion of the WebApiConfig.cs class (the Register method)is:

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

So far, so good. I can access the API methods using GET and a REST style Uri, such as:

localhost:51953/api/ordWarehouseFreight

to hit the 'Get()' method,

localhost:51953/api/ordWarehouseFreight/2716253

to hit the 'Get(int id)' method, and if I use

localhost:51953/api/ordWarehouseFreight/3928374,2716253

it actually hits the third one, 'Get(string idList)' (which, note, returns a LIST of records, not a single record like the 'Get(int id)' does).

Problem is, in some cases I want to get a list that may consist of only a single item (but is returned as a list, which is handled by my Angular 4 front end as a list of JSON objects). If I only pass in a single record id, I get a single item, not a list.

So, what I want to do is pass in Request params (not pure REST, I get that), like this:

localhost:51953/api/ordWarehouseFreight?idList=3928374,2716253

or

localhost:51953/api/ordWarehouseFreight?idList=3928374

and return a list in either case. However, when I use those URI's, the first Get method (with no parameters) is matched.

Finally to the question: what must I do to get the Web API to match up with the third option? From all I've read so far, here on SO and elsewhere, I'm doing all that's needed. Obviously not.

Aucun commentaire:

Enregistrer un commentaire