NiceToMytyuk
NiceToMytyuk

Reputation: 4277

How to route two get methods with same params in WebApi?

In my ApiController i had one GET method which was returning some data from DB.

Now i have to enlarge that controller by adding one more GET method which will return data from same database but formatted in another way so the parameters i'd pass to that method will be the same as from the 1st one.

I was trying to do the following:

Public Class CshController
    Inherits ApiController

    Public Function GetValoriCsh(ByVal npv As String, ByVal nc As String) As IEnumerable(Of Cshlvl)
        Dim csh As Cshlvl = New Cshlvl
        Return csh.ValoreCsh(npv, nc)
    End Function

    Public Function GetOperazioni(ByVal npv As String, ByVal nc As String) As IEnumerable(Of OperazioniCsh)
        Dim operazioni As OperazioniCsh = New OperazioniCsh
        Return operazioni.OperazioniCsh(npv, nc)
    End Function


End Class

So here come the issue, the api fails as there are two method which require same parameters so it doesn't know how to chose which i would to use.

actually i'm calling the following api by the following url api/csh/ is it possible in some way by calling api/csh/ to get data from GetValoriCsh and like by calling something like api/csh/operazioni/ to get data from GetOperazioni?

My WebApiConfig

Public Module WebApiConfig
    Public Sub Register(ByVal config As HttpConfiguration)
        ' Servizi e configurazione dell'API Web

        ' Route dell'API Web
        config.MapHttpAttributeRoutes()

        config.Routes.MapHttpRoute(
            name:="DefaultApi",
            routeTemplate:="api/{controller}/{id}",
            defaults:=New With {.id = RouteParameter.Optional}
        )

    End Sub
End Module

I've tryed to add <Route("api/csh/op")> above GetOperazioni but it had no effect.

Upvotes: 2

Views: 630

Answers (1)

Nkosi
Nkosi

Reputation: 247088

If using attribute routing it is all or nothing.

<RoutePrefix("api/csh")>
Public Class CshController
    Inherits ApiController

    'GET api/csh
    <HttpGet()>
    <Route("")>
    Public Function GetValoriCsh(ByVal npv As String, ByVal nc As String) As IEnumerable(Of Cshlvl)
        Dim csh As Cshlvl = New Cshlvl
        Return csh.ValoreCsh(npv, nc)
    End Function

    'GET api/csh/op
    <HttpGet()>
    <Route("op")>
    Public Function GetOperazioni(ByVal npv As String, ByVal nc As String) As IEnumerable(Of OperazioniCsh)
        Dim operazioni As OperazioniCsh = New OperazioniCsh
        Return operazioni.OperazioniCsh(npv, nc)
    End Function
End Class

Reference Attribute Routing in ASP.NET Web API 2

Upvotes: 1

Related Questions