Trigger Azure WebJob By Using WebAPI

In this article, I will discuss how to trigger/run an azure web job by using web api.

Introduction

 
In this article, I will discuss how to trigger/run an azure web job by using web api.
 
Azure web job is like a service that can run a task in the background. It doesn’t contain any UI and it is the same as our windows service.
 
The scenarios where we use azure web jobs are:-
  • Image processing or other cpu-intensive background work.
  • Queue processing.
  • File maintenance, such as aggregating or clean up log files.
  • Long-running tasks such as sending emails.

Prerequisite

  • Microsoft azure account.
  • Existing app service.
  • Existing web job but that is of type either triggered or scheduled.
So let’s create a sample application and after that, we will call GET and POST call.
 
Here I have created an asp.net application which contains two buttons as Get Web Job Call and Post Web Job Call and whose design looks like as below,
 
 
So first of all, we have to know about what the azure web job webapi looks like.
 
As you can see in this url, https://abc.azurewebsites.net belonged to my Azure app service.
 
As web job is present under Azure app service, so the web job api also slightly similar and looks like this, https://abc.scm.azurewebsites.net/api/.
 
After web job api url is formed, we need to add triggeredwebjobs at last and after that, we need to add our web job name.
 
So the complete web job api url looks like this,
 
 
 

Get Call Explanation

 
In the get call, we are retrieving the status of a web job. When we click on the get web job call button in UI then it will call getCallbtn_Click on the server-side and the code looks  as below,
  1. protected void getCallbtn_Click(object sender, EventArgs e) {  
  2.  var status = GetWebJobSync("triggeredwebjobs/Test");  
  3.  dynamic jsonStatus = JsonConvert.DeserializeObject(status);  
  4.  if (jsonStatus.latest_run != null) {  
  5.   var jobStatus = jsonStatus.latest_run.status;  
  6.  }  

The getCallbtn_Click method will call GetWebJobSync method bypassing the web job name and will return the status of the job.
  1. private string GetWebJobSync(string call) {  
  2.  string ApiUrl = "https://abc.scm.azurewebsites.net/api/";  
  3.  string result = string.Empty;  
  4.  string userPswd = "$demo" + ":" + "igQqdPY2pjbF6mTvo5WmjBpualiyqxBWgjgkaA0yc8tEo7Kbun7bRnddRvMb";  
  5.  userPswd = Convert.ToBase64String(Encoding.Default.GetBytes(userPswd));  
  6.  string baseURL = string.Format("{0}", call);  
  7.  try {  
  8.   using(var client = new HttpClient()) {  
  9.    client.BaseAddress = new Uri(ApiUrl);  
  10.    client.Timeout = TimeSpan.FromMinutes(30);  
  11.    client.DefaultRequestHeaders.Accept.Clear();  
  12.    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  13.    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", userPswd);  
  14.    var response = new HttpResponseMessage();  
  15.    response = client.GetAsync(baseURL).Result;  
  16.    result = response.IsSuccessStatusCode ? (response.Content.ReadAsStringAsync().Result) : response.IsSuccessStatusCode.ToString();  
  17.   }  
  18.   return result;  
  19.  } catch (Exception ex) {  
  20.   throw ex;  
  21.  }  
  22. }
The GetWebJobSync method uses a web api technique with a basic authentication approach to retrieve the status of the job.
 

Post Call Explanation

 
In the post call, we are running the web job. When we click on the post web job call button, then it will call postCallbtn_Click in the server-side and the code looks as below,
  1. protected void postCallbtn_Click(object sender, EventArgs e)  
  2. {  
  3.     var statusPOST = POSTWebJobSync();  
  4. }  
The postCallbtn_Click method will call the POSTWebJobSync method and return the response message.
  1. private HttpResponseMessage POSTWebJobSync() {  
  2.  string ApiUrl = "https://abc.scm.azurewebsites.net/api/";  
  3.  string call = "triggeredwebjobs/Test/run";  
  4.  string result = string.Empty;  
  5.  string userPswd = "$demo" + ":" + "igQqdPY2pjbF6mTvo5WmjBpualiyqxBWgjgkaA0yc8tEo7Kbun7bRnddRvMb";  
  6.  userPswd = Convert.ToBase64String(Encoding.Default.GetBytes(userPswd));  
  7.  var response = new HttpResponseMessage(HttpStatusCode.NotFound);  
  8.  try {  
  9.   using(var client = new HttpClient()) {  
  10.    client.BaseAddress = new Uri(ApiUrl);  
  11.    client.Timeout = TimeSpan.FromMinutes(30);  
  12.    client.DefaultRequestHeaders.Accept.Clear();  
  13.    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  14.    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", userPswd);  
  15.    response = client.PostAsync(call, new StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json")).Result;  
  16.   }  
  17.   return response;  
  18.  } catch (Exception ex) {  
  19.   throw ex;  
  20.  }  
  21. }
In both get and post call, we are retrieving the username and password from publish profile whose publishMethod="MSDeploy" which is present in the web app and shown below,
  1. <publishData>  
  2. <publishProfile profileName="demo - Web Deploy" publishMethod="MSDeploy" publishUrl="demo.scm.azurewebsites.net:443" msdeploySite="demo" userName="$demo" userPWD="igQqdPY2pjbF6mTvo5WmjBpualiyqxBWgjgkaA0yc8tEo7Kbun7bRnddRvMb" destinationAppUrl="http://demo.azurewebsites.net" SQLServerDBConnectionString="" mySQLDBConnectionString="" hostingProviderForumLink="" controlPanelLink="http://windows.azure.com" webSystem="WebSites"><databases />  
  3. </publishProfile>  
  4. <publishProfile profileName="demo - FTP" publishMethod="FTP" publishUrl="ftp://demo.ftp.azurewebsites.windows.net/site/wwwroot" ftpPassiveMode="True" userName="demo\$demo" userPWD="igQqdPY2pjbF6mTvo5WmjBpualiyqxBWgjgkaA0yc8tEo7Kbun7bRnddRvMb" destinationAppUrl="http://demo.azurewebsites.net" SQLServerDBConnectionString="" mySQLDBConnectionString="" hostingProviderForumLink="" controlPanelLink="http://windows.azure.com" webSystem="WebSites"><databases />  
  5. </publishProfile>  
  6. </publishData>  
Output
 
The output of get web job call status is shown below, 
 
 
Also, the output of post call status is shown below,
 
 
 
Note
  1. We can integrate the above code in asp.net, mvc or any other technologies.
  2. In place of abc and Test, you need to use your app service name and web job name.