You must Sign In to post a response.
  • Category: .NET

    Getting error while calling WEB API from my code.

    Hi Team,

    Am getting the compile time error "The type arguments for method 'System.Net.Http.HttpContentExtensions.ReadAsAsync<T>(System.Net.Http.HttpContent)'
    can not be inferred from the usage. Try specifying the type arguments explicitly." while try to implement in exactly in the line "responseMessage.Content.ReadAsAsync()" in below code.

    Any help is appreciated.

    HttpClient client = new HttpClient();
    string url = "http://localhost:4101/";
    client.BaseAddress = new Uri(url);
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage responseMessage = await client.GetAsync(url + "api/finance/getCostCentres");
    if (responseMessage.IsSuccessStatusCode)
    var responseData = responseMessage.Content.ReadAsAsync().Result;

    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    //List<Product> product = jsonSerializer.Deserialize<List<Product>>(responseData.ToString());
    //return View(product);
  • #764785
    1. You are trying the Async call. Are you doing Async method. Check the method created for Async call.

    2. Try the await also

    var responseData = (await) responseMessage.Content.ReadAsAsync().Result;

    By Nathan
    Direction is important than speed

  • #764828
    Hai Prabu,
    There could be many reasons of this error but quick checking can be the framework in which the web api and application uses.
    Try the below line of code in your config file to check the exact place of error:

    <compilation debug="true" targetFramework="4.0">

    Or the framework which you are targeting.
    Hope it will be helpful to you.

    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)

  • #764842

    Can you tell me in which line you are getting this exception? Is it a compile error or run time exception?

    Asheej T K
    Microsoft MVP[ASP.NET/IIS]
    DotNetSpider MVM

  • #764866
    You are getting this error because you have not provided the type of response your web api method is returning. Please see below example where I am specifying that the task will yield string output.

    var responseData = responseMessage.Content.ReadAsAsync<String>().Result;

    Here it returns a task that will yield an object of the type string.

    Miss. Jain
    Microsoft Certified Technology Specialist in .Net

Sign In to post your comments