Willy
Willy

Reputation: 10660

Consuming ASP.NET Web API REST Service in ASP.NET MVC using HttpClient

I have an ASP.NET MVC application from which I would like to consume an ASP.NET Web API REST service. So I have found a piece of code here.

In my case I would like to call ASP.NET Web API method (DumpIntoFile) from a method in a class in my ASP.NET MVC app (this class is not a controller). I need the execution not to continue until call to DumpIntoFile is completed and finished. How can I do it? I have never used async and await so I do not understand at all how they work.

    public void GetData()
    {
         Warehouse myData = new Warehouse();
         myData.id = 1111;
         myData.name = blabla;

         string path = "c:\temp";
         string filename = "myData.dat";

         // Stuff here
         this.DumpWarehouseDataIntoFile(myData, path, filename);
         // Some other stuff here
    }

    public async void DumpWarehouseDataIntoFile(Warehouse myData, string path, string filename)  // See Warehouse class later in this post
    { 
        //Hosted web API REST Service base url  
        string Baseurl = "http://XXX.XXX.XX.X:YYYY/";  

        using (var client = new HttpClient())  
        {  
            //Passing service base url  
            client.BaseAddress = new Uri(Baseurl);  

            client.DefaultRequestHeaders.Clear();  
            //Define request data format  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
              
            // Serialize parameter to pass to the asp web api rest service
            string jsonParam = Newtonsoft.JsonConvert.SerializeObject(myData);

            //Sending request to find web api REST service resource  using HttpClient

            // How can I pass parameters jsonParam, path and filename to below call??????? Concatenating it?
            HttpResponseMessage Res = await client.GetAsync("api/Warehouse/DumpIntoFile");  

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)  
            {  
               // Some other sftuff here
            }
         }
    }

The Warehouse object is as below:

public class Warehouse {
    public Warehouse();

    public int id { get; set; }
    public string name { get; set; }
    
    // some other stuff here
}

And web api rest controller with method:

public class MyWebApiController : ApiController
{
    public bool DumpIntoFile(string data, string path, string filename)
    {
        bool result;

        Warehouse myData = JsonConvert.DeserializeObject<Warehouse>(data);
        string myPath = path;
        string myFilename = filename;

        // Here rest of code

        return result;
    }
}

Also I am trying to do below:

  1. Avoid to hard-code the URL because if the ASP.NET Web API REST service is published in another server in a future, then I need to touch code, change it and publish again my ASP.NET MVC application. Maybe putting a the url in the web.config file and read from there?
  2. How can I pass the parameters jsonParam, path and filename to the web api rest service? concatenating it?

NOTES: I am using NET 4.5 and Visual Studio 2013.

Upvotes: 0

Views: 533

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457312

How can I do it? I have never used async and await so I do not understand at all how they work.

I recommend you read my async intro and follow up with async best practices. You'll learn two key things:

  • Avoid async void.
  • It's normal for async/await to "grow" through your codebase.

In your case, DumpWarehouseDataIntoFile should be async Task instead of async void. And that means GetData needs to await the task returned from DumpWarehouseDataIntoFile. Which means GetData should also be async Task. Which means things calling GetData should use await, etc.

Side note: By convention, asynchronous methods should end in Async.

public async Task GetDataAsync()
{
  Warehouse myData = new Warehouse();
  myData.id = 1111;
  myData.name = blabla;

  string path = "c:\temp";
  string filename = "myData.dat";

  // Stuff here
  await this.DumpWarehouseDataIntoFileAsync(myData, path, filename);
  // Some other stuff here
}

public async Task DumpWarehouseDataIntoFileAsync(Warehouse myData, string path, string filename)

Upvotes: 1

Related Questions