0
votes
I want to implement two get methods based on different id in web api service
eg:
// GET api/Data/5

 public List<Data> GetMyDatas(int id)
// GET api/Data/15
 public List<Data> GetMyDatas(int studid).

if i call this from my mvc controller how is it going to identify which get method it is getting called. is there a way to say this. I am having one mvc project and another mvc webapi1 project. i call the webmethod from my mvc project. VS 2010 , MVC 4 , Web API 1.

1
You'll need two different routes. You can't have matching routes with identical parameters unless you're using routing attributes: asp.net/web-api/overview/web-api-routing-and-actions/…timothyclifford
Does it support web api 1jubi
Yes this is possible in Web API 1 also but you will need to do so using a Nuget package.timothyclifford
i am not finding [RoutePrefix(")]jubi

1 Answers

2
votes

Your code is going to produce a compile time error because you have 2 methods with same name.

What you should do is, create a 2 seperate methods and use different url patterns for that.

With attribute routing enabled,

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
    public List<string> GetMyDatas(int id)
    {
        return new List<string> {"product 1", "value2", id.ToString()};
    }

    [Route("Students/{studId}")]
    public List<string> GetStudentDatas(int studid)
    {
        return new List<string> { "student", "Students", studid.ToString() };
    }
}

The first method can be accessed like yourSite/api/products/3 and second one can be accessed like yourSite/api/products/Students/3 where 3 can be replaced with a valid number

Another option is to add a second parameter to your single action method and based on the parameter, determine what data to return.

public List<string> GetMyDatas(int id,string mode="")
{
    //based on the mode value, return different data.
    return new List<string> {"product 1", "value2", id.ToString()};
}