简体   繁体   中英

How to Use application Insights REST API in Visual Studio MVC project

I want to retrieve all the data that is present in my resource on the azure portal. I have found out that there is a REST API for application insights that can help in retrieving the data. What I want is to get the data and generate a grid report on my web page which displays the events related information, that is, date, type, message and all the related information. I haven't worked with REST API's before and what I want as a help is a proper guideline to use this REST API in my MVC based web project in visual studio. If anyone can help will be a great assistance.

You can follow the steps below:

step 1: Get the Application ID and an API key.

Nav to your application insights -> API Access, see the screenshot(Please remember, when the api key is generated, write it down): 在此处输入图片说明

step 2: Understand the API Format, for details, refer to here :

Here is an example for get requests count in the last 6 hours:

https://api.applicationinsights.io/v1/apps/your-application-id/metrics/requests/count?timespan=PT6H

This part https://api.applicationinsights.io/v1/apps/ do not need to change.

Then input your-application-id which you get from last step.

Then you can specify metrics or events as per your demand.

This part requests/count , you can refer to this , screenshot below: 在此处输入图片说明

The last part ?timespan=PT6H , you can refer to this , screenshot below: 在此处输入图片说明

step 3: Write your code to call this api, like below:

public class Test
{
 private const string URL_requests = "https://api.applicationinsights.io/v1/apps/your-application-id/metrics/requests/count?timespan=PT6H";

 public string GetRequestsCount()
        {
            // in step 1, you get this api key
            string apikey = "flk2bqn1ydur57p7pa74yc3aazhbzf52xbyxthef";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("x-api-key", apikey);
            var req = string.Format(URL_requests);
            HttpResponseMessage response = client.GetAsync(req).Result;
            if (response.IsSuccessStatusCode)
            {
                // you can get the request count here
                return response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                return response.ReasonPhrase;
            }
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM