Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Asp.Net Web API endpoint from Azure function

I am trying to develop following scenario using Azure functions.

I have developed Asp.Net Web API which handles the Database related operation. Now, I want to implement a scheduler like functionality which will run once a day and will clean up junk data from database. I've created an endpoint for that in my Web API but I want to execute it on regular basis so I think to implement scheduler using Azure function's TimerTrigger function, is there any way to call my web api's endpoint in TimerTrigger function.

How to handle my api's authentication in Azure function?

Thanks

Update:

Based on mikhail's answer, finally I got the token using following code:

var client = new HttpClient();
client.BaseAddress = new Uri(apirooturl);

var grant_type = "password";
var username = "username";
var password = "password";

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("grant_type", grant_type),
    new KeyValuePair<string, string>("username", username),
    new KeyValuePair<string, string>("password", password)
});

var token = client.PostAsync("token", formContent).Result.Content.ReadAsAsync<AuthenticationToken>().Result;

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);

var response = await client.GetAsync(apiendpoint);
var content = await response.Content.ReadAsStringAsync();
like image 943
Rinkesh Avatar asked Mar 10 '17 16:03

Rinkesh


1 Answers

Azure Function is running in a normal Web App, so you can do pretty much anything there. Assuming you are on C#, the function body might looks something like

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", token);

var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
like image 76
Mikhail Shilkov Avatar answered Nov 17 '22 07:11

Mikhail Shilkov