请帮我完成家庭项目:我可以毫无问题地调用所有CRUD方法,但我不知道如何将非CRUD API调用定向到正确的端点。
尝试过这个:
var rentalEvent = rest.GetSingle<RentalEvent>($"api/rentalevent/boo/{licensePlate}");
要达到此目的:
[Route("/boo")]
[HttpGet("{licensePlate}")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
return new RentalEvent { RenterId = 88 }; //mock return class
}
控制器类的属性设置为:
[Route("api/[controller]")]
[ApiController]
在HttpGet
中指定的路由将覆盖您之前在Route
属性中设置的路由。尝试以下操作之一:
仅将HttpGet
用于整个路线:
[HttpGet("boo/{licensePlate}")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
return new RentalEvent { RenterId = 88 }; //mock return class
}
或者使用不带参数的HttpGet
,并将整个路由放在Route
属性中:
[Route("boo/{licensePlate}")]
[HttpGet]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
return new RentalEvent { RenterId = 88 }; //mock return class
}
有关详细信息,请参阅ASP.NET Web API中的属性路由。
最好只在一个地方定义Api路由。
[HttpGet("/boo")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
return new RentalEvent { RenterId = 88 }; //mock return class
}
对于get请求,通常应将字符串值用作查询中的可选参数。
api/rentalevent/boo?licensePlate=mylicense
在路由定义中放入任意字符串意味着不同的端点,而不是不同的参数值。