logo

ASP.NET - How to consume an Webservice asmx using xmlhttp and angularjs Javascript

Overview: This article explains how to call an asp.net webservice from AngularJS. You have to setup your web.config before you can consume any webservice api. Also, all code has to run on the server. No cross domain access is allowed, so don't put a url path to your webservice.

First add the httpProtocol custom header information.

httpProtocol additions to Web.config

<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*"/> <add name="Access-Control-Allow-Headers" value="Content-Type"/> </customHeaders> </httpProtocol> Add HttpGet and HttpPost webservice configurations to the Web.config <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols>

Building GuestBook.asmx webservice

Create a list of cData object with data and use the JavascriptSerializer to string the list of cData types.

    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Function GetObjectList(sCommand As String) As string
        Dim oList As New List(Of cData)
        Dim oData As cData
        dim TheSerializer as JavaScriptSerializer  = new JavaScriptSerializer()

        oData = New cData
        oData.element = "Thanks for visiting Listen Software Solutions. We hope you will become one of our valued customers, in the future."
        oList.Add(oData)
        Return (TheSerializer.serialize(oList))

    End Function
    Public Class cData
        Private privateElement As String
        Public Property element() As String
            Get
                Return Me.privateElement
            End Get
            Set(ByVal sValue As String)
                Me.privateElement = sValue
            End Set
        End Property
    End Class

Build your angular JS code

1. You have to specify the content-type in the xmlhttp call, otherwise, you will receive your json string wrapped in xml. XML is the default for the soap call, if the content-type : "application/json; charset=utf-8" is not added.

2. I always return my class objects as list from the web service. It makes it more easy to handle one or more returning objects. I then can access the object by index.

3. The xmlhttp parameters are stringify and posted to the web service api as key/value pairs created by JSON.stringify. You pass the parameters when invoking the send, method.

4. The handler function is invoke by the xmlhttp thread when results arrive. The status 4 indicates the http request was completed and status 200 indicates the http request was successful.

5. The client browser must be capable of supporting xmlhttp. If the user has this feature disabled than no data can be exchanged between the client and server.

6. The Web service.asmx wraps the json string with a {"d":"} component. I use JSON.parse(myjson.d); to remove d. Now I can access my element by index number.

<!DOCTYPE html>
<head>
    <title>consume JSON web service</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet">
    <script src="Scripts/angular.min.js"></script>

</head>
<body>
    <div>
        <div ng-app="serviceConsumer" ng-controller="questionsController">
        <span id="lblGreetings"></span>
        </div>
    
        <script src="Scripts/jquery-1.9.1.min.js"></script>
        <script src="Scripts/bootstrap.min.js"></script>

    </div>
    <script>

        var app = angular.module('serviceConsumer', []);

        app.controller('questionsController', function ($scope, $http) {
            
            var sUrl = "GuestBook.asmx/GetObjectList";

var params = JSON.stringify({ sCommand: 'test' });
var oReq = getXMLHttpRequest();


if (oReq != null) {
    oReq.open("POST", sUrl, true);
    oReq.setRequestHeader("Content-type", "application/json; charset=utf-8");
    oReq.setRequestHeader("Content-length", params.length);
    oReq.setRequestHeader("Connection", "close");
    oReq.onreadystatechange = handler;
    oReq.send(params);
}
else {
    window.console.log("AJAX (XMLHTTP) not supported.");
}

function handler()
{
    if (oReq.readyState == 4 ) {
        if (oReq.status == 200) {
            console.log(oReq.responseText);
            var myjson = JSON.parse(oReq.responseText);
            var myjson2=JSON.parse(myjson.d);
            var sMessage='';
            for (i=0;  i<= myjson2.length-1; i++)
            {
            sMessage=sMessage + myjson2[i].element + '<br>';
            }
            lblGreetings=document.getElementById('lblGreetings');
            lblGreetings.innerHTML=sMessage;
        }
    }
}

function getXMLHttpRequest() 
{
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            return null;
        }
    }
}



});                        
    </script>
</body>
</html>  

s