Home > front end >  Routing non-CRUD method to API Endpoint
Routing non-CRUD method to API Endpoint

Time:12-09

Please, help me with my home project: I can call all CRUD methods without problems, but I don’t know how to direct non-CRUD API calls to the proper endpoint.

Tried this:

var rentalEvent = rest.GetSingle<RentalEvent>($"api/rentalevent/boo/{licensePlate}");

To reach this:

[Route("/boo")]
[HttpGet("{licensePlate}")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

The Controller class’ attributes are set up as:

[Route("api/[controller]")] 
[ApiController]

CodePudding user response:

The route specified in HttpGet with overrides what you've set before in the Route attribute. Try one of the following:

Use only HttpGet with the whole Route:

[HttpGet("boo/{licensePlate}")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

Or use HttpGet without an argument and put the whole route in the Route attribute:

[Route("boo/{licensePlate}")]
[HttpGet]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

For more info, see Attribute Routing in ASP.NET Web API.

CodePudding user response:

Best to just have the Api route defined in one place.

[HttpGet("/boo")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

For a get request a string value should generally be used as an optional parameter in the query.

api/rentalevent/boo?licensePlate=mylicense

Putting an arbitrary string in the route definition implies a different endpoint rather than a different parameter value.

  • Related