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

Time:11-27

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.

CodePudding user response:

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..
    }
}
  • Related