Several methods in the same Apicontroller

Asked

Viewed 538 times

1

I am creating a web Api project and wanted to put a set of methods in the same Controllerapi.

But in the methods, I pass a Json object as a parameter. And as their structure looks similar (see example), the controller gets confused because he thinks they are all the same and so always calls the first method.

How can I fix this ?

Thanks in advance

Example:

public class MeuController : ApiCOntroller
{
    public List<Series> ObterSeries (ParametroSeries parametros)
    { ... }

    public List<Contas> ObterContas (ParametroContas parametros)
    { ... }
}

The call is being made as follows:

$.post("api/MeuController/ObterContas", { Identificacao: '12.234.567/0001-89' })
       .done(function (data) {  ...  })
});

$.post("api/MeuController/ObterSeries", { Identificacao: '12.234.567/0001-89' })
       .done(function (data) {  ...  })
});

Obs: Used json because there are other parameters that may or may not be informed

  • Place the code where you are passing JSON, to see what the problem is.

  • And add the language tag you are using. Just click [Edit] below the question.

  • How are the route settings on Webapiconfig.Cs?

  • config.Routes.Maphttproute( name: "Defaultapi", routeTemplate: "api/{controller}/{id}", defaults: new { id = Routeparameter.Optional } ); config.Routes.Maphttproute( name: "Meuapi", routeTemplate: "api/{controller}/{action}/{parameters}" );

1 answer

2

I’d say the real problem is your routes.

As the first route that satisfies the request is used, and in your case the default route that is used by REST was mapped first it may be being used, while its API follows the RPC style.

I would say that there are two alternatives in your case, first if you use only RPC you can remove the default route, this will remove the support for REST and everything else should continue as it already is.

Now if you want to use REST and RPC in the same project then you need to change one of the routes, for example by changing the routeTemplate of MeuApi for rpc/{controller}/{action}/{parametros} and then make the same modification in the call by javascript, changing the api for rpc at the address.

It may also be that simply changing the order in which the routes are registered solves the problem, but I can’t say for sure if it would cause problem for an API using REST.

  • I got it. I’ll see it right as I go. Thank you very much for your personal help !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.