[Solved] Passing parameter to ASP.Net Web API Controller Value are always null

makumbi
 
on Mar 13, 2021 04:25 AM
2044 Views

Passing parameters from URL returns empty and error.

I have been using this example from your link to pass parameters from my URL from the address bar to my API so as to return specific records. But after passing them i get error below and no record is returned.

An exception of type 'System.NullReferenceException' occurred in NEWEMPAPI.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

http://localhost:53489/api/CustomerAPI/GetCustomers/?Name=Sula&City=Namagoma

 

Imports System.Data.SqlClient
Imports System.Net
Imports System.Web.Http

Namespace Controllers

    Public Class CustomerAPIController
        Inherits ApiController

        <Route("api/CustomerAPI/GetCustomers")>
        <HttpGet>
        Public Function GetCustomers(customer As CustomerModel) As List(Of Customer)
            ' Public Function GetCustomers(Names As String, City As String)
            ' As List(Of Customer)

            Dim customers As New List(Of Customer)()
            Dim constr As String = ConfigurationManager.ConnectionStrings("SCHOOLConnectionString1").ConnectionString

            Using con As New SqlConnection(constr)
                Dim query As String = "SELECT CustomerID,ContactName,City FROM Customers WHERE (ContactName LIKE @Name + '%' OR @Name IS NULL) AND (City = @City OR @City IS NULL)"
                Using cmd As New SqlCommand(query)
                    cmd.Connection = con
                    ' cmd.Parameters.AddWithValue("@Name", If(Not String.IsNullOrEmpty(customer.Name), customer.Name, CType(DBNull.Value, Object)))
                    ' cmd.Parameters.AddWithValue("@City", If(Not String.IsNullOrEmpty(customer.City), customer.City, CType(DBNull.Value, Object)))


                    cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = customer.Name
                    cmd.Parameters.Add("@City", SqlDbType.NVarChar).Value = customer.City

                    con.Open()
                    Using sdr As SqlDataReader = cmd.ExecuteReader()
                        While sdr.Read()
                            customers.Add(New Customer() With {
                                .CustomerID = sdr("CustomerID").ToString(),
                                .ContactName = sdr("ContactName").ToString(),
                                .City = sdr("City").ToString()
                            })
                        End While
                    End Using
                    con.Close()
                End Using
            End Using

            Return customers
        End Function

        Public Class Customer
            Public Property CustomerID() As String
            Public Property ContactName() As String
            Public Property City() As String
        End Class
    End Class
End Namespace

Below is the customer model class i also created.

Public Class CustomerModel
    Public Property Name() As String
    Public Property City() As String
End Class

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 13, 2021 06:15 AM
on Dec 30, 2021 10:43 AM

Hi makumbi,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br />
Country: <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="Search" />
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" />
        <asp:BoundField DataField="ContactName" HeaderText="ContactName" />
        <asp:BoundField DataField="City" HeaderText="City" />
    </Columns>
</asp:GridView>

Model

Public Class CustomerModel
    Public Property Name As String
    Public Property Country As String
End Class

Namespaces

Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Http
Imports System.Net
Imports System.Web.Script.Serialization

Controller

Public Class CustomerAPIController
    Inherits ApiController
    <Route("api/CustomerAPI/GetCustomers")>
    <HttpPost>
    Public Function GetCustomers(customer As CustomerModel) As List(Of Customer)
        Dim customers As New List(Of Customer)()
        Dim constr As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
        Using con As New SqlConnection(constr)
            Dim query As String = "SELECT CustomerID,ContactName,City,Country FROM Customers WHERE (ContactName LIKE @Name + '%' OR @Name IS NULL) AND (Country = @Country OR @Country IS NULL)"
            Using cmd As New SqlCommand(query)
                cmd.Connection = con
                cmd.Parameters.AddWithValue("@Name", customer.Name)
                cmd.Parameters.AddWithValue("@Country", customer.Country)
                con.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(New Customer() With {
                            .CustomerID = sdr("CustomerID").ToString(),
                            .ContactName = sdr("ContactName").ToString(),
                            .City = sdr("City").ToString(),
                            .Country = sdr("Country").ToString()
                        })
                    End While
                End Using
                con.Close()
            End Using
        End Using

        Return customers
    End Function
End Class

Code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.PopulateGridView()
    End If
End Sub

Protected Sub Search(ByVal sender As Object, ByVal e As EventArgs)
    Me.PopulateGridView()
End Sub

Private Sub PopulateGridView()
    Dim apiUrl As String = "http://localhost:61977/api/CustomerAPI"
    Dim input As Object = New With {
        .Name = txtName.Text.Trim(),
        .Country = txtCountry.Text.Trim()
    }
    Dim inputJson As String = New JavaScriptSerializer().Serialize(input)
    Dim client As WebClient = New WebClient()
    client.Headers("Content-type") = "application/json"
    client.Encoding = Encoding.UTF8
    Dim json As String = client.UploadString(apiUrl & "/GetCustomers", inputJson)
    gvCustomers.DataSource = (New JavaScriptSerializer()).Deserialize(Of List(Of Customer))(json)
    gvCustomers.DataBind()
End Sub

Public Class Customer
    Public Property CustomerID As String
    Public Property ContactName As String
    Public Property City As String
    Public Property Country As String
End Class

Screenshot