locked
Need help to consume ASP.NET Web Service return JSON Data RRS feed

  • Question

  • User-557095619 posted

    I've ASP.NET Web Service as following,

    Employee.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// Summary description for Employee
    /// </summary>
    public class Employee
    {
    	public Employee()
    	{
    		//
    		// TODO: Add constructor logic here
    		//
    	}
    
        // Instance Variables 
        public String ID;
        public String Name;
        //int Gender;
        public String Gender;
        public String Salary; 
      
        // Constructor Declaration of Class 
        public Employee(String ID, String Name, 
                      String Gender, String Salary) 
        {
            this.ID = ID; 
            this.Name = Name; 
            this.Gender = Gender; 
            this.Salary = Salary; 
        } 
    
    }

    ERPDOTNET.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    //using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    //using System.Web;
    //using System.Web.Services;
    using System.Web.Services.Protocols;
    
    //using System;
    using System.Configuration;
    //using System.Data;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Script.Services;
    //using System.Web.Services;
    
    
    /// <summary>
    /// Summary description for ERPDOTNET
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ERPDOTNET : System.Web.Services.WebService {
    
        public AuthHeader Authentication;
    
        public ERPDOTNET () {
    
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
    
        //[WebMethod]
        //public string HelloWorld() {
        //    return "Hello World";
        //}
    
        /*
        [SoapHeader("Authentication", Required = true)]
        [WebMethod(Description = "Returns some sample data")]
        public DataSet SensitiveData()
        {
            DataSet data = new DataSet();
    
            //Do our authentication
            //this can be via a database or whatever
            if (Authentication.Username == "test" && Authentication.Password == "test")
            {
                //they are allowed access to our sensitive data
    
                //just create some dummy data
                DataTable dtTable1 = new DataTable();
                DataColumn drCol1 = new DataColumn("Data", System.Type.GetType("System.String"));
                dtTable1.Columns.Add(drCol1);
    
                DataRow drRow = dtTable1.NewRow();
                drRow["Data"] = "Sensitive Data";
                dtTable1.Rows.Add(drRow);
                dtTable1.AcceptChanges();
    
                data.Tables.Add(dtTable1);
    
    
    
            }
            else
            {
                data = null;
            }
    
            return data;
        }
    
        */
    
        [SoapHeader("Authentication", Required = true)]
        [WebMethod(Description = "Returns some employee data")]
        public void AuthGetEmployeeById(string employeeId)
        {
    
            Employee employee = new Employee();
    
            //string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            //using (SqlConnection con = new SqlConnection(cs))
            //{
            //    SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
            //    cmd.CommandType = CommandType.StoredProcedure;
            //    SqlParameter parameter = new SqlParameter();
            //    parameter.ParameterName = "@Id";
            //    parameter.Value = employeeId;
            //    cmd.Parameters.Add(parameter);
            //    con.Open();
            //    SqlDataReader rdr = cmd.ExecuteReader();
            //    while (rdr.Read())
            //    {
            //        //employee.ID = Convert.ToInt32(rdr["Id"]);
            //        //employee.Name = rdr["Name"].ToString();
            //        //employee.Gender = rdr["Gender"].ToString();
            //        //employee.Salary = Convert.ToInt32(rdr["Salary"]);
            //    }
    
            //}
    
            if (Authentication.Username == "test" && Authentication.Password == "test")
            {
    
                if (employeeId == "AB123456789")
                {
                    employee.ID = "AB123456789";
                    employee.Name = "Sharul Nizam";
                    employee.Gender = "Lelaki";
                    employee.Salary = "12000";
                }
    
                else if (employeeId == "AB374656478")
                {
                    employee.ID = "AB374656478";
                    employee.Name = "Haris Haram Jadah";
                    employee.Gender = "Lelaki";
                    employee.Salary = "6000";
                }
    
                else
                {
                    employee.ID = string.Empty;
                    employee.Name = string.Empty;
                    employee.Gender = string.Empty;
                    employee.Salary = string.Empty;
                }
    
            }
    
    
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(employee));
    
        }
    
    
        [WebMethod]
        public void GetEmployeeById(string employeeId)
        {
    
            Employee employee = new Employee();
    
            //string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            //using (SqlConnection con = new SqlConnection(cs))
            //{
            //    SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
            //    cmd.CommandType = CommandType.StoredProcedure;
            //    SqlParameter parameter = new SqlParameter();
            //    parameter.ParameterName = "@Id";
            //    parameter.Value = employeeId;
            //    cmd.Parameters.Add(parameter);
            //    con.Open();
            //    SqlDataReader rdr = cmd.ExecuteReader();
            //    while (rdr.Read())
            //    {
            //        //employee.ID = Convert.ToInt32(rdr["Id"]);
            //        //employee.Name = rdr["Name"].ToString();
            //        //employee.Gender = rdr["Gender"].ToString();
            //        //employee.Salary = Convert.ToInt32(rdr["Salary"]);
            //    }
    
            //}
            if (employeeId == "AB123456789")
            {
                employee.ID = "AB123456789";
            employee.Name = "Sharul Nizam";
            employee.Gender = "Lelaki";
            employee.Salary = "12000";
            }
    
            else if (employeeId == "AB374656478")
            {
                employee.ID = "AB374656478";
                employee.Name = "Haris Haram Jadah";
                employee.Gender = "Lelaki";
                employee.Salary = "6000";
            }
    
            else
            {
                employee.ID = string.Empty;
                employee.Name = string.Empty;
                employee.Gender = string.Empty;
                employee.Salary = string.Empty;
            }
    
    
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(employee));
    
        }
    
    
       
    
        public class AuthHeader : SoapHeader
        {
            public string Username;
            public string Password;
        }
    
        
    }
    

    ERPDOTNET.asmx

    <%@ WebService Language="C#" CodeBehind="~/App_Code/ERPDOTNET.cs" Class="ERPDOTNET" %>
    

    I tried to consume GetEmployeeById using html as follow

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    
        <script type="text/javascript">
    
            $('#btnGetEmployee').click(function () {
              
    
                var empId = $('#txtId').val();
    
                $.ajax({
                    url: 'http://10.1.101.45/erpdotnet/ERPDOTNET.asmx/GetEmployeeById',                
                    data: { employeeId: empId },
                    method: 'post',
                    dataType: 'json',
                    success: function (data) {
    
                        $('#txtName').val(data.d.Name);
                        $('#txtGender').val(data.d.Gender);
                        $('#txtSalary').val(data.d.Salary);
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
    
        </script>
        <style type="text/css">
            .style1
            {
                width: 100%;
            }
            .style2
            {
                width: 34px;
            }
            .style3
            {
                width: 149px;
            }
            .style4
            {
                width: 87px;
            }
        </style>
    </head>
    <body>
    
        <table class="style1">
            <tr>
                <td class="style2">
                    ID:</td>
                <td class="style3">
                    <input id="txtId" type="text" style="width:150px" /></td>
                <td>&nbsp;
                    <input id="btnGetEmployee" type="button" value="Get Employee" /></td>
            </tr>
        </table>
       
        <br/>
            <table class="style1">
                <tr>
                    <td class="style4">
                        Name:</td>
                    <td>
                        &nbsp;<input id="txtName" type="text" /></td>
                </tr>
                <tr>
                    <td class="style4">
                        Gender:</td>
                    <td>
                        &nbsp;<input id="txtGender" type="text" /></td>
                </tr>
                <tr>
                    <td class="style4">
                        Salary:</td>
                    <td>
                        &nbsp;<input id="txtSalary" type="text" /></td>
                </tr>
            </table>
        
    
    
    
        
    
    </body>
    </html>
    

    The result is - NO RETURN. Please help

    Another help, please help me to consume AuthGetEmployeeById using html as well. This time with Authentication

    Thursday, July 4, 2019 11:48 AM

Answers

  • User475983607 posted

    There are several issues with the design.  The biggest is you've configured a SOAP Header "Authentication" but you are trying to consume JSON using REST.  REST and SOAP are very different.  You need to figure out what direction direction you are going.

    If you decide on REST then you'll need to enable client scripting by removing the comment from the [ScriptService] attribute.

    /// <summary>
    /// Summary description for ERPDOTNET
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ERPDOTNET : System.Web.Services.WebService {

    And come up with a different "Authentication" design.

    I recommend moving away from SOAP and going to Web API if you want to build a REST service.  Web API is much easier to implement and has everything you need to secure service endpoints.   With ASMX is you'll need to design and build the security bits.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 4, 2019 12:06 PM