WebAPI 2:使用错误参数调用默认 GET ALL
WebAPI 2 : Default GET ALL is invoked with wrong parameter
我正在使用带有 EF 的 WebAPI 2 和来自 visual studio 的脚手架 webapi 控制器。
每个控制器都使用 4 个默认动词(GET、PUT、DELETE、POST)和 5 个操作创建。虽然有两个版本的 GET 操作。
IQueryable<entity> GetEntities ()
Task<IHttpActionResult> GetEntity(GUID key)
// 默认是 int id 但我改成 guid.
我正在为控制器使用属性路由和路由前缀。只是一些花哨的关键字,以便更好地管理 url。 [RoutePrefix("api/v3/Company")]
问题:
理想情况下,当在 url 中发送错误参数时,它应该 return 错误,但它不会引发错误,而是返回到没有 parameter.while 的操作,如果我发送错误的 GUID,显示错误。
就像我打电话一样:
http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
显示正确的结果。
当我打电话时:
http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e96500
(错误的密钥)
它设置回GetEntity()
函数并显示所有记录
当我打电话时:
http://localhost:8080/api/v3/Company/1
(不是 GUID 长度参数)
它做同样的事情并显示所有记录。
我正在使用属性 [Route("{id:guid}")]
如果能得到一些指导,我将不胜感激!
很可能路由默认返回基于约定的映射。
您需要明确地在操作上应用路由属性,让路由知道它是默认路由 GET
[RoutePrefix("api/v3/Company")]
public class CompanyController : ApiController {
//GET api/v3/Company
[HttpGet]
[Route("")] //Default Get
public IQueryable GetEntities() { ... }
//GET api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
[HttpGet]
[Route("{id:guid}")] // ALSO NOTE THAT THE PARAMETER NAMES HAVE TO MATCH
public Task<IHttpActionResult> GetEntity(Guid id) { ... }
//...other code removed for brevity
}
确保在 web api 配置中启用属性路由
config.MapHttpAttributeRoutes();
我正在使用带有 EF 的 WebAPI 2 和来自 visual studio 的脚手架 webapi 控制器。 每个控制器都使用 4 个默认动词(GET、PUT、DELETE、POST)和 5 个操作创建。虽然有两个版本的 GET 操作。
IQueryable<entity> GetEntities ()
Task<IHttpActionResult> GetEntity(GUID key)
// 默认是 int id 但我改成 guid.
我正在为控制器使用属性路由和路由前缀。只是一些花哨的关键字,以便更好地管理 url。 [RoutePrefix("api/v3/Company")]
问题:
理想情况下,当在 url 中发送错误参数时,它应该 return 错误,但它不会引发错误,而是返回到没有 parameter.while 的操作,如果我发送错误的 GUID,显示错误。
就像我打电话一样:
http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
显示正确的结果。
当我打电话时:
http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e96500
(错误的密钥)
它设置回GetEntity()
函数并显示所有记录
当我打电话时:
http://localhost:8080/api/v3/Company/1
(不是 GUID 长度参数)
它做同样的事情并显示所有记录。
我正在使用属性 [Route("{id:guid}")]
如果能得到一些指导,我将不胜感激!
很可能路由默认返回基于约定的映射。 您需要明确地在操作上应用路由属性,让路由知道它是默认路由 GET
[RoutePrefix("api/v3/Company")]
public class CompanyController : ApiController {
//GET api/v3/Company
[HttpGet]
[Route("")] //Default Get
public IQueryable GetEntities() { ... }
//GET api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
[HttpGet]
[Route("{id:guid}")] // ALSO NOTE THAT THE PARAMETER NAMES HAVE TO MATCH
public Task<IHttpActionResult> GetEntity(Guid id) { ... }
//...other code removed for brevity
}
确保在 web api 配置中启用属性路由
config.MapHttpAttributeRoutes();