In my web api application, I want to enable clients to make requests, using the same path, but pass different type of parameters.
For example:
public class MyController : ApiController
{
[HttpDelete]
public IHttpActionResult Delete(int id) {..}
[HttpDelete]
public IHttpActionResult Delete2(Guid id) {..}
[HttpDelete]
public IHttpActionResult Delete3(string id) {..}
}
I want the url for each method to be similar, for example:
api/MyController/1
api/MyController/abc etc..
Is this possible? Iv'e tried alot of combinations with ActionName
attribute and Routing configuration, but nothing seemed to work.
Thanks
You can use attribute routing for this. For example:
[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) {..}
}
If you do this then the request url will be:
http://yoursever/mycontroller/delete/123
http://yoursever/mycontroller/delete/abc
http://yoursever/mycontroller/delete/91c74f8f-d981-4ee1-ba36-3e9416bba202
You need to provide a Route
with different parameter types for each of your methods:
[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) {..}
}
Of course you have to enable attribute routing if you haven't already.
The Order
property for the Route
attribute ensures that the route templates are checked in the correct order so that an int
value will not match the string route.
Yes, this is possible. Try setting the route as a decoration
.
example:
[Route("DeleteThis/{id}")]
[HttpDelete]
public IHttpActionResult DeleteThis(int id)
{
return Ok();
}
[Route("NowDeleteThis/{name}")]
[HttpDelete]
public IHttpActionResult DeleteThis(string name)
{
return Ok();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.