在我的web api应用程序中,我想让客户端使用相同的路径发出请求,但是传递不同类型的参数。
例如:
container.Register<HttpContextBase>(() =>
new HttpContextWrapper(HttpContext.Current),
Lifestyle.Scoped);
container.Register<DataSource>(() =>
{
var httpContext = container.GetInstance<HttpContextBase>();
return MasterDataSource.WithUser(httpContext?.User?.Identity?.Name);
},
Lifestyle.Scoped);
我希望每个方法的网址都相似,例如:
public class MyController : ApiController
{
[HttpDelete]
public IHttpActionResult Delete(int id) {..}
[HttpDelete]
public IHttpActionResult Delete2(Guid id) {..}
[HttpDelete]
public IHttpActionResult Delete3(string id) {..}
}
这可能吗?我尝试了很多具有api/MyController/1
api/MyController/abc etc..
属性和路由配置的组合,但似乎没有任何效果。
谢谢
答案 0 :(得分:6)
您可以使用attribute routing。例如:
[RoutePrefix("MyController")]
public class MyController : ApiController
{
[HttpDelete]
[Route("delete/{id:int}")]
public IHttpActionResult Delete(int id) {..}
[HttpDelete]
[Route("delete/{id:guid}")]
public IHttpActionResult Delete2(Guid id) {..}
[HttpDelete]
[Route("delete/{id:alpha}")]
public IHttpActionResult Delete3(string id) {..}
}
如果您这样做,那么请求网址将是:
http://yoursever/mycontroller/delete/123
http://yoursever/mycontroller/delete/abc
http://yoursever/mycontroller/delete/91c74f8f-d981-4ee1-ba36-3e9416bba202
答案 1 :(得分:3)
您需要为每个方法提供具有不同参数类型的Route
:
[RoutePrefix("api/MyController")]
public class MyController : ApiController
{
[HttpDelete]
[Route("{id:int}", Order = 1)]
public IHttpActionResult Delete(int id) {..}
[HttpDelete]
[Route("{id:guid}", Order = 2)]
public IHttpActionResult Delete2(Guid id) {..}
[HttpDelete]
[Route("{id}", Order = 3)]
public IHttpActionResult Delete3(string id) {..}
}
当然,如果你还没有,你必须enable attribute routing
Order
属性的Route
属性可确保以正确的顺序检查路由模板,以使int
值与字符串路由不匹配。
答案 2 :(得分:0)
是的,这是可能的。尝试将路线设为decoration
。
示例:
[Route("DeleteThis/{id}")]
[HttpDelete]
public IHttpActionResult DeleteThis(int id)
{
return Ok();
}
[Route("NowDeleteThis/{name}")]
[HttpDelete]
public IHttpActionResult DeleteThis(string name)
{
return Ok();
}