Skip to content

Instantly share code, notes, and snippets.

@codingoutloud
Created March 25, 2018 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingoutloud/77b2731a3efbe18225749969c4bcf647 to your computer and use it in GitHub Desktop.
Save codingoutloud/77b2731a3efbe18225749969c4bcf647 to your computer and use it in GitHub Desktop.
Get User Agent Summary from within an Azure Function using whatismybrowser.com API
#r "Newtonsoft.Json"
using System.Net;
using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public static async Task<string> GetUserAgentSummaryAsync(HttpRequest req, TraceWriter log)
{
const bool verbose = false;
var agents = req.Headers["User-Agent"];
if (verbose) log.Info($"AGENTS COUNT = {agents.Count}");
if (verbose) log.Info($"{agents}");
var agentjson = $"{{ \"user_agent\": \"{agents[0]}\" }}";
if (verbose) log.Info($"AGENT JSON = [{agentjson}]");
const string useragent_apikey_header = "X-API-KEY";
const string useragent_apikey_location = "HOSTHEADER_APIKEY";
var useragent_apikey = System.Environment.GetEnvironmentVariable(useragent_apikey_location); // CONFIGURE IN YOUR ENVIRONMENT
if (verbose) log.Info($"API KEY LENGTH = {useragent_apikey.Length}");
const string useragent_apiurl = "https://api.whatismybrowser.com/api/v2/user_agent_parse";
using (var httpClient = new HttpClient()) // okay for low-scale; else see https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri(useragent_apiurl),
Method = HttpMethod.Post,
Content = new StringContent(agentjson, Encoding.UTF8, "application/json")
};
request.Headers.Add(useragent_apikey_header, useragent_apikey);
// not needed, not harmful: request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpResponseMessage response = await httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode(); // may throw
var result = await response.Content.ReadAsStringAsync();
if (verbose) log.Info($"RESULT = {result}");
if (verbose) log.Info($"AGENTS = {agents}");
var json = JObject.Parse(result);
bool parsedOk = ((string) (json["result"]["code"])) == "success";
bool is_abusive = (bool) (json["parse"]["is_abusive"]);
if (is_abusive || ! parsedOk)
{
throw new Exception($"Could not parse user agent ({parsedOk}) or was malformed ({is_abusive})");
}
var browser = (string) json["parse"]["software_name"];
var os = (string) json["parse"]["operating_system_name"];
var text = $"{browser} on {os}";
if (verbose) text = $"{text} [details: {result}]";
return text;
}
}
}
public static async Task<IActionResult> Run(HttpRequest req, TraceWriter log)
{
log.Info("Detect and return summary user agent for caller of this Azure Function");
string summaryUserAgent;
try
{
summaryUserAgent = await GetUserAgentSummaryAsync(req, log);
return (ActionResult) new OkObjectResult(summaryUserAgent);
}
catch (Exception ex)
{
return new BadRequestObjectResult(ex.Message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment