Search code examples
asp.net-mvcasp.net-coreasp.net-mvc-4asp.net-web-api

How to Call Web API from Another MVC Project with two Parameter one in header and second in body


I want to call api action from from mvc project but i have an issue API action have two parameter one in header and second in body.


Solution

  • You create a HttpClient object and set the header parameter

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:64189/api/");
        
        //your header parameter name and value
        client.DefaultRequestHeaders.Add("hdrname", "hdrvalue"); 
        
        //HTTP GET
        var responseTask = client.GetAsync("youraction?param1=abc"); //Action Name
        responseTask.Wait();
    
        var result = responseTask.Result;
        if (result.IsSuccessStatusCode)
        {
            // Use your class model to receive the data from the API
            var readTask = result.Content.ReadAsAsync<IList<YourModel>>();
            readTask.Wait();
    
            var r = readTask.Result;
        }
        else //web api sent error response 
        {
            //log response status here..
        }
    }