简体   繁体   中英

Retrieving 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 retrieve 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?

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)]

将通过ajax发布的数据更改为

JSON.stringify({ "email": "test.mail@gmail.com" });

Your WebMethod has to be static . Its an rule of WebMethod .

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

And also use the application/json as content-type if you want to send the JSON to the server and please ensure to stringify before sending them.

data: JSON.stringify({Email: 'test.mail@gmail.com'});

If above solution didnt helped please provide the inner exception details of the ajax request.

If you need return a JSON from a WebMethod without MVC don't return anything and using Context.Response.Write(JSON);

[WebMethod]
public void method()
{
   ...
   Context.Response.Write(dt.ToJSON());
}

https://andersnordby.wordpress.com/2012/10/16/returning-json-from-a-net-4-0-web-service/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM