Would it be possible to do send an async HTTP request from an automation script? For example using the HttpClient-class? I want to call an external API based on a correlation rule.
I've tried experimenting a bit, including using sub-scripts but I can't really get any output.
Is there some other best-practice?
Hi Robin,
I've used below code in the past to send a async HTTP request
public class Script
{
private static HttpClient httpClient = new HttpClient();public void Run(Engine engine)
{
var result = GetResult();
}private static myClass GetResult()
{
var response = httpClient.PostAsync(new Uri("url"), content).Result;var responseBodyJson = response.Content.ReadAsStringAsync().Result;
var jsonObject = JsonConvert.DeserializeObject<myClass>(responseBodyJson);return jsonObject;
}
}
Hi Robin, I’ve made some changes to my code
– HttpClient is now a shared field. See more details for this change in https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
– I don’t use the .Wait function anymore since the .Result function already makes it synchronously. In general automation scripts are executed sequentially, so therefore we should try to avoid async code as much as possible.
That makes sense.
It was the .Wait-function that solved it, thanks Jens!