Reputation: 98
In a WEB API controller, can we have the same method name with different HTTP verbs like HTTPGET/HTTPPOST etc. If so, can you please elaborate on what configuration is required in RouteConfig. (I have an angular Front end application trying to invoke these methods)
Here is the example.
[HttpGet]
public string Test()
{
return "Success";
}
[HttpPost]
public string Test()
{
return "Success";
}
Here is my routeconfig
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
Upvotes: 1
Views: 2888
Reputation: 403
You can add two methods with different parameters.
[HttpPost]
public string Test(string data)
{
return "Success";
}
[HttpGet]
public string Test()
{
return "Success";
}
Hope this is what you are looking for.
Upvotes: 1
Reputation: 33381
In a WEB API controller, can we have the same method name with different HTTP verbs like HTTPGET/HTTPPOST etc
I want to rephrase this:
Can I make GET and POST request to the same Url and have handled appropriately.
Yes. You can use Route
attribute for both api controller methods to handle same Url, one for GET
and another for POST
decorated with HttpGet
and HttpPost
attributes appropriately .
[HttpGet]
[Route("api/mymethod")]
public string SomeMethod()
{
return "from somemethod - get";
}
[HttpPost]
[Route("api/mymethod")]
public string SomeAnotherMethod()
{
return "from some another method - post";
}
Upvotes: 4
Reputation: 15847
You can't have methods with the same signatures defined in the same class. The compiler won't let you do that! However why do you need this? If the operation is POST then you have to have some way to get the data that the browser/client is posting.
[HttpPost]
public string Test(string data)
{
return "Success";
}
If there is no data to post then just do a simple get to another method.
Upvotes: 0