ralessi
ralessi

Reputation: 33

Call async .NET 4.5 web service from jquery

I'm trying to understand how to call from jquery 1.9.1 a .net 4.5 web service (asmx) which is using async/await. The js code is classic:

$.ajax({
    type: "POST",
    url: "ws/UpdCategory",
    data: strData,
    async: true,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    complete: saveCategory_onComplete
});

the web service in ws.cs, code behind of ws.asmx:

[WebMethod]
public async Task<int> UpdCategory(string jsonData)
{
    JsonGenericResponse objWmJson = new JsonGenericResponse();
    objWmJson.IsInError = "true";
    try
    {
        JavaScriptSerializer objJss = new JavaScriptSerializer();
        Dictionary<string, string> objDict = objJss.Deserialize<Dictionary<string, string>>(jsonData);
        DataIfCloudEspresso objData = new DataIfCloudEspresso();
        //
        StringBuilder objBuilder = new StringBuilder();
        objBuilder.Append("<?xml version=" + (char)39 + "1.0" + (char)39 + " encoding=" + (char)39 + ConfigurationService.XMLEncoding + (char)39 + "?>");
        objBuilder.Append("<Category>");
        .....various fields
        objBuilder.Append("</Category>");
        // the row below call the method on Data Access Layer
        int updatedCount = await objData.UpdCategory(objBuilder.ToString());
        return updatedCount;
    }
}

and finally the DAL method:

public async Task<int> UpdCategorieArticoli(string xmlData)
{
    try
    {
        using (SqlConnection objConn = new SqlConnection(base.ConnectionString))
        {
            using (SqlCommand cmdADO = new SqlCommand("spUpd_Category", objConn))
            {
                cmdADO.Parameters.Add(new System.Data.SqlClient.SqlParameter("@XMLDoc", SqlDbType.Text));
                cmdADO.Parameters["@XMLDoc"].Value = xmlData;
                cmdADO.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", SqlDbType.Int));
                cmdADO.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
                //
                cmdADO.CommandType = CommandType.StoredProcedure;
                //
                await objConn.OpenAsync().ConfigureAwait(false);
                return await cmdADO.ExecuteNonQueryAsync().ConfigureAwait(false);
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
    }
}

The problem is this: the DAL method if is called from a Page_Load , for example, works without problems; instead when called from the web service (which is called from javascript) the code hangs on the line await cmdADO.ExecuteNonQueryAsync().

I suppose that the problem is the context switch from the client (the js code from the browser) and the code behind that works on the server, i don't understand how to solve this issue. I have tried various code found googling , but no solution.

The obvious scope is to maximize the use of async code for the max performance.

I have tried to write an old style BeginExecuteNonQuery with a callback, but i have not found a solution on how to communicate the result to the calling web service from the EndExecuteNonQuery.

Upvotes: 2

Views: 3723

Answers (2)

svick
svick

Reputation: 244757

According to comments on Is it possible to use async/await in webmethod asmx service, ASMX simply doesn't support async. That's why your code doesn't work. And it has nothing to do with jQuery being asynchronous too.

Upvotes: 2

xmidPOE
xmidPOE

Reputation: 111

The jQuery async is by it self an async. This is what is happening. When you call the web service it executes the data access logic async and returns http response to the web service OK that means that the method has been executed with success but it returns no result.

When you call it from Page_Load that means that the render of the page will for all of the async methods to finish to perform the rendering.

So bottom line is not to use async on the web service because you have async on the jQuery side.

Upvotes: 1

Related Questions