3

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

  • 1
    If they are all doing the same thing, I suggest creating a custom class (object) to hold each of these (nullable) properties, and using 1 route. – Mark C. May 25 '16 at 12:25

3 Answers3

5

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
Nasreddine
  • 36,610
  • 17
  • 75
  • 94
3

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.

Federico Dipuma
  • 17,655
  • 4
  • 39
  • 56
0

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();
        }
Beshoy Hanna
  • 611
  • 2
  • 9
  • 29