1

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}");
1
  • Look at the Route attribute. Commented Jan 22, 2016 at 20:25

3 Answers 3

5

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";
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

Thank you the response. Yes you are right lets say we have post method with different parameters..can we have that working in API? get method with out any input param and Post with an input param and method name is same?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.