I am using the .Net MVC4 Web API to (hopefully) implement a RESTful api. I need to pass in a few parameters to the system and have it perform some action, then return a lis
[Route("api/controller/{one}/{two}")]
public string Get(int One, int Two)
{
return "both params of the root link({one},{two}) and Get function parameters (one, two) should be same ";
}
Both params of the root link({one},{two}) and Get function parameters (one, two) should be same
I think the easiest way is to simply use AttributeRouting
.
It's obvious within your controller, why would you want this in your Global WebApiConfig
file?
Example:
[Route("api/YOURCONTROLLER/{paramOne}/{paramTwo}")]
public string Get(int paramOne, int paramTwo)
{
return "The [Route] with multiple params worked";
}
The {}
names need to match your parameters.
Simple as that, now you have a separate GET
that handles multiple params in this instance.
Now you can do this by simply using
public string Get(int id, int abc)
{
return "value: " + id + " " + abc;
}
this will return: "value: 5 10"
if you call it with https://yourdomain/api/yourcontroller?id=5&abc=10
I know this is really old, but I wanted the same thing recently and here's what I found...
public HttpResponseMessage Get([FromUri] string var, [FromUri] string test) {
var retStr = new HttpResponseMessage(HttpStatusCode.OK);
if (var.ToLower() == "getnew" && test.ToLower() == "test") {
retStr.Content = new StringContent("Found Test", System.Text.Encoding.UTF8, "text/plain");
} else {
retStr.Content = new StringContent("Couldn't Find that test", System.Text.Encoding.UTF8, "text/plain");
}
return retStr;
}
So now in your address/URI/...
http(s)://myURL/api/myController/?var=getnew&test=test
Result: "Found Test"
http(s)://myURL/api/myController/?var=getnew&test=anything
Result: "Couldn't Find that test"
Using GET or POST is clearly explained by @LukLed. Regarding the ways you can pass the parameters I would suggest going with the second approach (I don't know much about ODATA either).
1.Serializing the params into one single JSON string and picking it apart in the API. http://forums.asp.net/t/1807316.aspx/1
This is not user friendly and SEO friendly
2.Pass the params in the query string. What is best way to pass multiple query parameters to a restful api?
This is the usual preferable approach.
3.Defining the params in the route: api/controller/date1/date2
This is definitely not a good approach. This makes feel some one date2
is a sub resource of date1
and that is not the case. Both the date1
and date2
are query parameters and comes in the same level.
In simple case I would suggest an URI like this,
api/controller?start=date1&end=date2
But I personally like the below URI pattern but in this case we have to write some custom code to map the parameters.
api/controller/date1,date2