1

I want to call my web service from JScript using AJAX, and found the error.

the error is:

{Message: "No parameterless constructor defined for type of 'System.String'.",…} ExceptionType: "System.MissingMethodException" Message: "No parameterless constructor defined for type of 'System.String'." StackTrace: " at System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) ↵ at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) ↵ at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) ↵ at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary2 rawParams) ↵ at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams) ↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"

here is my AJAX

function retrieveToken(){var BodyToken = JSON.stringify({
    "userName": "crm"
});
var param1= {
    Token : BodyToken
}

var param2 = JSON.stringify({
    param1
});
$.ajax({
    url: "http://10.23.64.43:8035/iFrameIntegration.asmx/getToken?",
    data: "Token="+JSON.stringify({"userName":"crm"}),
    contentType: "application/json; charset=utf-8",
    type: 'GET',
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        alert("Error");
    }
});}

and here is my web service

public class iFrameIntegration : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void getToken(string Token)
    {
        var request = (HttpWebRequest)WebRequest.Create("http://10.23.64.37:8080/ACCMWS/member/SSOInit");
        var DataObject = Token;
        var data = Encoding.ASCII.GetBytes(DataObject);
        request.Method = "POST";
        request.ContentType = "application/json";
        //request.Headers["Content-Type"] = "application/json";
        request.Headers["userId"] = "Svc_CRM";
        request.Headers["loginType"] = "Internal";
        request.Headers["token"] = "54a93982adf51adfb81885ddbbb1874e271605ce";

        try
        {
            request.ContentLength = data.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(data, 0, data.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
            Stream resultStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(resultStream);
            string readerResponse = reader.ReadToEnd();
            var result = JsonConvert.DeserializeObject<RetrieveSSOTokenResult>(readerResponse);
            //return result.data.ssotokenList[0].ssoToken;
            PrintValue(result.data.ssotokenList[0].ssoToken);
        }
        catch(Exception ex)
        {
            ex.Message.ToString();
        }

    }

    private void PrintValue(object obj)
    {
        Context.Response.Write(obj.ToString());
    }
}}

and also here is my class

namespace FWDiFrameIntegration{
public class RetrieveSSOTokenResult
{
    public string status { get; set; }
    public string message { get; set; }
    public Data data { get; set; }
}

public class Data
{
    public Ssotokenlist[] ssotokenList { get; set; }
}

public class Ssotokenlist
{
    public string loginType { get; set; }
    public string userName { get; set; }
    public string userId { get; set; }
    public string ssoToken { get; set; }
    public long expiryTime { get; set; }
}}

please advise

UPDATE.

finally, able to resolved based on Gaurav information. the error comes, because i'm using public void. here is my update web service

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getToken()
    {
        var request = (HttpWebRequest)WebRequest.Create("http://10.23.64.37:8080/ACCMWS/member/SSOInit");
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Headers["userId"] = "Svc_CRM";
        request.Headers["loginType"] = "Internal";
        request.Headers["token"] = "54a93982adf51adfb81885ddbbb1874e271605ce";

        string result = string.Empty;
        try
        {
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = "{ \"userName\": \"crm\"}";
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            try
            {
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    if (request.HaveResponse && response != null)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            var resultTokenAwal = reader.ReadToEnd();
                            var resultToken = JsonConvert.DeserializeObject<RetrieveSSOTokenResult>(resultTokenAwal);
                            result = resultToken.data.ssotokenList[0].ssoToken;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)e.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string error = reader.ReadToEnd();
                            result = error;
                        }
                    }

                }
            }
        }
        catch(Exception ex)
        {
            ex.Message.ToString();
        }
        return result;
    }
Denis
  • 21
  • 4

1 Answers1

0

Ok after little research finally I got it working by changing the method verb to POST instead of GET as we can not(or gets too complicated) send the complex data type in GET requests. Here is code:

 [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void getToken(object Token)
    {

    }

Here is ajax code:

$.ajax({
            url: "/iFrameIntegration.asmx/getToken",
            data: JSON.stringify({ Token: { userData: 'crm' } }),
            contentType: "application/json; charset=utf-8",
            type: 'POST',
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("Error");
            }
        });
Gaurav
  • 782
  • 5
  • 12
  • from AJAX, I have to send the data like this: {"userName":"crm"}. then my web service, this is as the parameter. – Denis Jan 18 '19 at 08:55
  • then it should be like data: {token : { userName : "crm"}} – Gaurav Jan 18 '19 at 08:57
  • Tried this, but no luck. the error becomes : "Invalid JSON primitive: crm." and also check on fiddler, the request become : http://10.23.64.43:8035/iFrameIntegration.asmx/getToken?&Token=crm – Denis Jan 18 '19 at 09:02
  • Tried the second one, still no luck. the error becomes : "Invalid web service call, missing value for parameter: 'Token'.". – Denis Jan 18 '19 at 09:08
  • Just go to your service and add [FromBody] in front of parameter. Something like this public void getToken([FromBody] object Token). Also it should be object as you have Jobject in it. – Gaurav Jan 18 '19 at 09:10
  • Gaurav, can you give me the example? – Denis Jan 18 '19 at 09:28
  • Here is my another post where I solve similar problem https://stackoverflow.com/questions/54124446/cant-call-delete-function-from-ajax-jquery-to-asp-net-api-function/54141788#54141788 – Gaurav Jan 18 '19 at 09:29
  • I'm not using web api, but using asmx web method. Actually, the call from AJAX already can be retrieve by web service, and the return is JSON, thats why, I'm decentralize the result,and only get the token. – Denis Jan 18 '19 at 09:32
  • @Denis I made an update to my answer and its working fine on my machine let me know if it helps. – Gaurav Jan 18 '19 at 10:10
  • hi @Gaurav, still the same error. No parameterless constructor defined for type of 'System.String'. – Denis Jan 21 '19 at 04:15
  • Hi @Gaurav, I able to fix this using an object like you said. but, for the result, I still have a problem and posted in another thread (https://stackoverflow.com/questions/54284220/deserialize-object-when-ajax-call-asmx-web-service). can you help me to advise. – Denis Jan 21 '19 at 06:02