0

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.

3
  • So you mean await client.GetAsync("api/Warehouse/DumpIntoFile"); doesn't wait for the method call to finish? what do you mean by that? what's in DumpIntoFile ? Commented Dec 2, 2020 at 14:38
  • @Dave I have updated my post. Regarding to await client.GetAsync I am implementing it just right now but I haven't been able to test it yet. I wonder if await will wait and not continue to the next line of code until call to web api rest service completes and finishes. Am I right? Commented Dec 2, 2020 at 14:47
  • 1
    Ralph (sorry, i couldn't get your name in @ mentions) - ok, yes this should wait for the request to finish. Whenever you use Async method, you need to await them otherwise, the execution won't wait for Async methods to be finished. Test await client.GetAsync("api/Warehouse/DumpIntoFile"); out to see if its waiting or not. If you're seeing unexpected output, there would be something that's not being awaited in DumpIntoFile Commented Dec 2, 2020 at 14:51

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

ok,so as you said,it means things calling GetData should use await,and so on.The problem with this is that all the methods implicated in the chain should need to be marked as async and perform an await on the method called.But my method who calls GetData is not marked as async so it is a problem for me,if I do not mark it as async it does not work.In fact what I want is to make a syncrhonous call to web api rest service method DumpIntoFile,not an asynchrounous call.I need to wait until DumpIntoFile has finished and completed in order to execute the next lines of code.So how can I achieve this?
@Ralph: Making it synchronous will make the thread wait. Making it (properly) asynchronous will make the code wait (without blocking the thread). You can think of await as "asynchronous wait". So "I need to wait until DumpIntoFile has finished and completed in order to execute the next lines of code" is accomplished by using await.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.