Search code examples
c#asp.netangularweb-servicesasmx

Asp.net WebService Cannot convert object of type 'System.Int32' to ty…neric.IDictionary`2[System.String,System.Object]'


I've been trying to call a WebService using Angular

I already tested the WebService and Send a request using Postman and it worked correctly.

Here is the code for the WebService

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Temperature : System.Web.Services.WebService
    {
        [WebMethod]
        public double Farenheit(double celsius)
        {
            return  (celsius * 9) / 5 + 32;
        }
        [WebMethod]
        public double Celsius(double fahrenheit)
        {
            return (fahrenheit - 32) * 5 / 9;
        }
    }

And this is my Angular Code

const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',

      })
    };

this.http.post('https://localhost:44389/Temperature.asmx/Celsius', 50,  httpOptions)
    .subscribe(res => {
      console.log('Data: ' + res);

    })

The Method Accept an Int data type. And I'm passing 50 integer. So why does I'm receiving this error. I don't understand Why

ExceptionType: "System.InvalidOperationException"
Message: "Cannot convert object of type 'System.Int32' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'"
StackTrace: "   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Serial

And here is the screenshot of the POSTMAN requset

enter image description here


Solution

  • You need to pass:

    {fahrenheit: 50}
    

    rather than:

    50
    

    This is because your existing code passes up a number but doesn't indicate which parameter it maps to. By explicitly mentioning fahrenheit the server-side is able to map the 50 value to the appropriate method parameter.