Calling methods in class controller (asp.net web.api) to work while changing parameter name

1

I have a question on using the asp.net web api with angularJS that follows below.

I have 2 methods in my controller class (ItemsController.cs):

public void Put(int id, [FromBody]Item value)
{
}

and

[ActionName("UpdateItemFees")]
[HttpPost]
public void UpdateItemFees(int id, [FromBody]Item value)
{         
}

My call on the client is:

$http.put('/api/Itens/Put/' + $scope.osID, item)
$http.post('/api/Itens/UpdateItemFees/' + $scope.osID, item)

This works without problems. The problem is when I change the name of a parameter in these methods, then the system no longer calls the method in the Controls Items:

public void Put(int osID, [FromBody]Item value)
{
}

and

[ActionName("UpdateItemFees")]
[HttpPost]
public void UpdateItemFees(int osID, [FromBody]Item value)
{         
}

The errors are:

  • 'http://local/api/Itens/Put/3443'.
    

    and

  • 'http://local/api/Itens/UpdateItemFees/3443'.
    

    What is wrong with changing the method parameter name (from "id" to "osID")?

    I have other methods on the page, like GET that are working perfectly, even with parameters with custom names (this I find strange).

    Thank you in advance.

        
  • asked by anonymous 24.09.2014 / 20:54

    1 answer

    1

    Basically, the route.

    Normally, it is configured like this:

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{action}/{id}",
         defaults: new { id = System.Web.Http.RouteParameter.Optional }
       );
    

    That is, the route DefaultApi knows a route whose next parameter is id , and the Controller trusts this.

    If you called the request as follows:

    http://local/api/Itens/Put/?osID=3443
    

    Notice that it will work, because then you force ModelBinder to read a parameter called osID that was not necessarily set in the route.

    There are a few ways to solve it. One is defining a route that accepts osID as a parameter without having to place the parameter name in the request address. The other is to use the way I indicated above.

        
    24.09.2014 / 22:48