Results 1 to 5 of 5

Thread: error while returning values from API after passing parameters

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2020
    Location
    Kampala
    Posts
    8

    error while returning values from API after passing parameters

    Please help am having a problem with returning values from webapi by passing parameters

    Code:
    Imports System.Data.SqlClient
    Imports System.Net
    Imports System.Web.Http
    
    Namespace Controllers
        Public Class HandlerVBLoadtermController
            Inherits ApiController
    
            <Route("api/HandlerVBLoadterm/GetCustomersJSON/{customerid}/{customerid2}")>
            <HttpGet>
            Public Function GetCustomersJSON(customerId As String, customerId2 As String) As IHttpActionResult
                Dim customers As New List(Of Customer)()
                Using conn As New SqlConnection()
                    conn.ConnectionString = ConfigurationManager.ConnectionStrings("KABOJJAConnectionString").ConnectionString
                    Using cmd As New SqlCommand()
                        cmd.CommandType = CommandType.StoredProcedure
                        cmd.CommandText = "Gettermnew"
                        cmd.Parameters.AddWithValue("@p", customerId)
                        cmd.Parameters.AddWithValue("@s", customerId2)
                        cmd.Connection = conn
                        conn.Open()
                        Using sdr As SqlDataReader = cmd.ExecuteReader()
                            While sdr.Read()
                                customers.Add(New Customer With {
                                  .Account = If(IsDBNull(sdr("Admno")), String.Empty, sdr("Admno")),
                                  .Expressed = If(IsDBNull(sdr("Expressed")), String.Empty, sdr("Expressed"))})
                            End While
                        End Using
    
                        conn.Close()
                    End Using
                    Return Ok(customers)
                End Using
            End Function
        End Class
    
    
        Public Class Customer
            Public Property Account() As String
            Public Property Expressed() As String
    
        End Class
    End Namespace
    When i run this URL
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/0782911364/Father
    this returns Json data but when i runs this URL below with the ? operand it doesnot return any data

    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON?customerid=0782911364&customerid2=Father
    I get this error when i try to run it
    Code:
    "No HTTP resource was found that matches the request URI 'http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON?customerid=0782911364&customerid2=Father'."
    Below is my webapi.config details

    Code:
    Imports System.Net.Http
    Imports System.Web.Http
    Imports Microsoft.Owin.Security.OAuth
    Imports Newtonsoft.Json.Serialization
    
    Public Module WebApiConfig
        Public Sub Register(config As HttpConfiguration)
          ' Web API configuration and services
          ' Configure Web API to use only bearer token authentication.
          config.SuppressDefaultHostAuthentication()
          config.Filters.Add(New HostAuthenticationFilter(OAuthDefaults.AuthenticationType))
    
          ' Web API routes
          config.MapHttpAttributeRoutes()
    
            config.Routes.MapHttpRoute(
                name:="DefaultApi",
                routeTemplate:="api/{controller}/{id}",
                defaults:=New With {.id = RouteParameter.Optional}
            )
            config.Formatters.Add(New CustomJSONFormatter())
            ' Adding formatter for XML   
            ' config.Formatters.XmlFormatter.MediaTypeMappings.Add(New QueryStringMapping("type", "xml", New MediaTypeHeaderValue("application/xml")))
        End Sub
    End Module

  2. #2
    Frenzied Member PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Newport, UK
    Posts
    1,338

    Re: error while returning values from API after passing parameters

    You have defined a route to the API with
    Code:
    <Route("api/HandlerVBLoadterm/GetCustomersJSON/{customerid}/{customerid2}")>
    This means you need to provide a url that matches this pattern, the url
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/0782911364/Father
    matches this pattern and therefore it works.

    The second url you are trying
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON?customerid=0782911364&customerid2=Father
    is trying to match a URL of
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON
    which isn't the same thing and doesn't exist - hence the 404.

    Why do you want to use querystrings rather than route parameters? The first url is a lot cleaner and easier than the querystring based one anyway.

    If you really do want to use querystrings you could make the two route parameters optional...

  3. #3

    Thread Starter
    New Member
    Join Date
    Sep 2020
    Location
    Kampala
    Posts
    8

    Re: error while returning values from API after passing parameters

    Quote Originally Posted by PlausiblyDamp View Post
    You have defined a route to the API with
    Code:
    <Route("api/HandlerVBLoadterm/GetCustomersJSON/{customerid}/{customerid2}")>
    This means you need to provide a url that matches this pattern, the url
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/0782911364/Father
    matches this pattern and therefore it works.

    The second url you are trying
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON?customerid=0782911364&customerid2=Father
    is trying to match a URL of
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON
    which isn't the same thing and doesn't exist - hence the 404.

    Why do you want to use querystrings rather than route parameters? The first url is a lot cleaner and easier than the querystring based one anyway.

    If you really do want to use querystrings you could make the two route parameters optional...
    thanks for your observation how can i route parameter in this case of mine which areas can i edit to achieve what i want because i wanted to use ? operand in my statement because you are saying that it is the most easier aspect

  4. #4

    Thread Starter
    New Member
    Join Date
    Sep 2020
    Location
    Kampala
    Posts
    8

    How to pass parameter to api with ? sign

    This is the error it returns yet if i run it here in this format
    Code:
    http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/0782911364/Father
    on my web browser i dont get any problem please help
    because when i pass it from the code it gives the error below
    Code:
    {"Message":"No HTTP resource was found that matches the request URI 'http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/?customerId=0782911364&customerId2=Father'."}
    api code
    Code:
    Imports System.Data.SqlClient
    Imports System.Net
    Imports System.Web.Http
    
    Namespace Controllers
        Public Class HandlerVBLoadtermController
            Inherits ApiController
    
            <Route("api/HandlerVBLoadterm/GetCustomersJSON/{customerid}/{customerid2}")>
            <HttpGet>
            Public Function GetCustomersJSON(customerId As String, customerId2 As String) As IHttpActionResult
                Dim customers As New List(Of Customer)()
                Using conn As New SqlConnection()
                    conn.ConnectionString = ConfigurationManager.ConnectionStrings("KABOJJAConnectionString").ConnectionString
                    Using cmd As New SqlCommand()
                        cmd.CommandType = CommandType.StoredProcedure
                        cmd.CommandText = "Gettermnew"
                        cmd.Parameters.AddWithValue("@p", customerId)
                        cmd.Parameters.AddWithValue("@s", customerId2)
                        cmd.Connection = conn
                        conn.Open()
                        Using sdr As SqlDataReader = cmd.ExecuteReader()
                            While sdr.Read()
                                customers.Add(New Customer With {
                                  .Account = If(IsDBNull(sdr("Admno")), String.Empty, sdr("Admno")),
                                  .Expressed = If(IsDBNull(sdr("Expressed")), String.Empty, sdr("Expressed"))})
                            End While
                        End Using
    
                        conn.Close()
                    End Using
                    Return Ok(customers)
                End Using
            End Function
        End Class
    
    
        Public Class Customer
            Public Property Account() As String
            Public Property Expressed() As String
    
        End Class
    End Namespace
    iam using B4ax for android development
    below
    Code:
     Dim phone,sx As String
       phone="0782911364"
       sx="Father"
    	'Dim json As JSONGenerator
    	'json.Initialize(Subscriptiondetailsm)
    	'Dim contentr As String = json.ToString
    	'Depends on okHttputils library
    	Dim clientb As HttpJob
    	clientb.Initialize("",Me)
    
    	clientb.Download2("http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/", Array As String("customerId",phone,"customerId2", sx))
    	'clientb.GetRequest.SetContentType("application/json")    'set the header as json
    	'clientb.GetRequest.SetContentEncoding("UTF8")
               
    	Wait For Jobdone(clientb As HttpJob)
       
    	If clientb.Success Then
    		Dim Resultd As String = clientb.GetString
    		Dim data As JSONParser
    		data.Initialize(Resultd)
    		Log(Resultd)
    		'Dim product As Map = data.NextObject
    		Else
    		Log(Resultd)
    	End If
    below is my route config
    Code:
    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web
    Imports System.Web.Mvc
    Imports System.Web.Routing
    
    Public Module RouteConfig
        Public Sub RegisterRoutes(ByVal routes As RouteCollection)
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
    
            routes.MapRoute(
                name:="Default",
                url:="{controller}/{action}/{id}",
                defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
            )
        End Sub
    End Module
    also my webapiconfig

    Code:
    Imports System.Net.Http
    Imports System.Web.Http
    Imports Microsoft.Owin.Security.OAuth
    Imports Newtonsoft.Json.Serialization
    
    Public Module WebApiConfig
        Public Sub Register(config As HttpConfiguration)
          ' Web API configuration and services
          ' Configure Web API to use only bearer token authentication.
          config.SuppressDefaultHostAuthentication()
          config.Filters.Add(New HostAuthenticationFilter(OAuthDefaults.AuthenticationType))
    
          ' Web API routes
          config.MapHttpAttributeRoutes()
    
            config.Routes.MapHttpRoute(
                name:="DefaultApi",
                routeTemplate:="api/{controller}/{id}",
                defaults:=New With {.id = RouteParameter.Optional}
            )
            config.Formatters.Add(New CustomJSONFormatter())
            ' Adding formatter for XML   
            ' config.Formatters.XmlFormatter.MediaTypeMappings.Add(New QueryStringMapping("type", "xml", New MediaTypeHeaderValue("application/xml")))
        End Sub
    End Module

  5. #5
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,286

    Re: How to pass parameter to api with ? sign

    Code:
    clientb.Download2("http://192.168.14.205/KABOJJAAPPAPI/api/HandlerVBLoadterm/GetCustomersJSON/", Array As String("customerId",phone,"customerId2", sx))
    That's because you're passing them as parameters rather than as part of the URL...
    Try assembling it as a complete string first, then pass that to the method, without the array parameter.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width