CedricCornelis CedricCornelis - 5 months ago 53
jQuery Question

Retreiving data from an ASP.NET webservice using Ajax-call in AngularJS

EDIT: added some extra methods to make things a bit more clear

I am trying to retreive data from an ASP.NET webservice in C# using Ajax-calls in AngularJS. Our webmethod looks like following:

[WebMethod]
public User getUserByEmail(String Email)
{
return new User().getUserByEmail(Email);
}


Below, you will find our exact .getUserByEmail(Email)-method:

public User getUserByEmail(String Email)
{
User u = null;

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["socceronlineConnectionString"].ConnectionString))
{
SqlCommand command = new SqlCommand("SELECT * FROM dbo.tbl_User WHERE Email = 'nick.cornelis@student.vives.be'", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while(reader.Read())
{
Debug.WriteLine("UserId: " + reader[0] + " \n ClubId: " + reader[1] + " \n Language: " + reader[4] + " \n Passwordhash: " + reader[11] + " \n FirstName: " + reader[12] + " \n LastName: " + reader[13] + " \n Email: " + reader[14] + " \n");

u = saveUser(reader);
}
}
finally
{
reader.Close();
}
}

return u;
}


Here we save our data in our domain-object.

Our domain-class is as follows:

private User saveUser(SqlDataReader reader)
{
User u = new User();

if (reader[0] != DBNull.Value)
{
u.UserId = (int)reader[0];
}
if (reader[1] != DBNull.Value)
{
u.ClubId = (int)reader[1];
}
if (reader[4] != DBNull.Value)
{
u.Language = (String)reader[4];
}
if (reader[11] != DBNull.Value)
{
u.Passwordhash = (String)reader[11];
}
if (reader[12] != DBNull.Value)
{
u.FirstName = (String)reader[12];
}
if (reader[13] != DBNull.Value)
{
u.LastName = (String)reader[13];
}
if (reader[14] != DBNull.Value)
{
u.Email = (String)reader[14];
}

return u;
}
}


As you can see, the getUserByEmail-method connects to the database and retreives the right information, that part works just fine. Now we are trying to access this database via AngularJS. Here is our AJAX-call:

$http({
method: 'POST',
url: "http://localhost:19067/UserList.asmx/getUserByEmail",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {Email: 'test.mail@gmail.com'}
}).success(function (data, status, headers, config) {

alert("succes");

}).error(function (data, status, headers, config) {

alert("no succes");

});


When I'm trying this last method, I'm receiving a 500 server error.
When I'm trying to receive all email-adresses through another method via GET, it all works fine.
What is the right method to do a parameterized ajax-call to my webservice?

Answer

Try this:

$http({
        method: 'POST',
        url: "http://localhost:19067/UserList.asmx/getUserByEmail",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        data: $.param({Email: "test.mail@gmail.com"})
    }).success(function(data,status,headers,config){ });

A few things need to be pointed out though. If you still have this issue after using this piece of code (500 error) you might have to tweak your server settings. When accessing your webserver via xhr you must allow the origin to access the resource. (Cross-origin resource sharing - CORS)

In order to do so in ASP you'll need to add the following to your config

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

Note that, if this is a single-purpose service, it would be a wise idea to specify the (source)domain instead of this wildcard. An other thing, if you want to limit the access to POST only requests you might want to consider adding following attribute to your method:

    [ScriptMethod(UseHttpGet =false)]