0

I've come to some strange behaviour using web api. I'm using attribute routing, and making post on server. Controller:

    [Route("names")]
    public ResultDTO SaveData(SomeDTO dto)
    {
       //somecode
        ...
    } 

and i'm calling it

     $http.post('/api/mycontroller/names', $scope.model.dto).success(function 
      (data) { ...

It's working. However, if I rename my method

    [Route("names")]
    public ResultDTO GetData(SomeDTO dto)
    {
       //somecode
        ...
    } 

it's not working and I get HTTP 405 error The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access,

However it's working if I change calling from $http.post to $http.get

Obviously, I won't name my method starting with GetSomeMethod if I'm posting data, but I'm curious, shouldn't defined route

   [Route("names")]

work with $http.post, no matter how I actually call method that will handle that post? More specific, why $http.post won't work if I named my method GetSomething, but it will if I change method name to, for example, GotSomething or SaveSomething?

ekad
  • 14,436
  • 26
  • 44
  • 46
Error
  • 815
  • 1
  • 19
  • 33
  • Possible duplicate of [Web API route to action name](https://stackoverflow.com/questions/18661946/web-api-route-to-action-name) – Pr.Dumbledor Jul 24 '17 at 14:58

2 Answers2

4

Try to add route attribute

[HttpPost]

and then you can name your action as you wish.

Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with Get..., such as GetContact or GetAllContacts. This convention applies only to GET, POST, PUT, and DELETE methods.

See more here

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • I already try that and it's working, but I'm curious why it's not working if I named methog starting with Get? – Error Jul 24 '17 at 10:17
  • @Error framework is using naming convention. Because method is prefixed with `Get` it assumes you want to make a get if you do not explicitly state what verb the action expects by using the verb attributes – Nkosi Jul 24 '17 at 10:20
  • But shouldn't my explicit [Route("names")] tell Web API which method to execute, no matter how I named that method? I mean, in this example, does it mean that Web API finds mythod which I want to execute, but because of naming convention it refusses because of method name and returns HTTP 405? – Error Jul 24 '17 at 10:37
  • In webapi you should specify name of method and http verb – Roman Marusyk Jul 24 '17 at 11:26
0

Use proper verbs for $http.post(***) - [HttpPost] and for $http.get(***) - [HttpGet]

Kundan Rai
  • 75
  • 1
  • 1
  • 7