1

I'm trying to get some of api users request information like the device that they use and the operating system so I tried it like this :

private string GetDeviceInfo()
    {
        var userAgent = HttpContext.Current.Request.UserAgent;
        var uaParser = Parser.GetDefault();
        var c = uaParser.Parse(userAgent);
        return c.Device + "|" + c.OS + "|" + c.UserAgent;
    }

but the HttpContext.Current.Request.UserAgent is always null !. I searched about it and tried this link , could you please tell me what is wrong?

Community
  • 1
  • 1
Mohamed Farrag
  • 1,682
  • 2
  • 19
  • 41
  • have you stepped thru the code..? if so what values are in `userAgent` also take a look at this posting.. http://www.codeproject.com/Articles/42347/How-to-Detect-Browser-Capabilities-in-ASP-NET – MethodMan Dec 01 '14 at 15:49
  • may be your client is not sending the user-agent header. how are you accessing your api? @Figo – Zohaib Aslam Dec 01 '14 at 15:53
  • @DJKRAZE `userAgent` is `null` as the `HttpContext.Current.Request.UserAgent` is `null` it throws an exception of kind `System.ArgumentNullException: Value cannot be null. Parameter name: input at System.Text.RegularExpressions.Regex.Match(String input) at UAParser.Parser.Parsers.||c_DisplayClass43`1.|Create|b41(String input)` ! – Mohamed Farrag Dec 01 '14 at 16:07
  • @ZohaibAslam my client is calling the api directly `/api/request`, should I force the client to send these information ? if so how ? – Mohamed Farrag Dec 01 '14 at 16:09
  • try this site...http://www.yetanotherforum.net/forum/posts/t8877-Bug-Fixes-For-The-Bugs-I-ve-Found#post36155 – MethodMan Dec 01 '14 at 16:12
  • yes @Figo, you have to, otherwise user-agent will be null, otherwise you can try some browser, it will automatically set headers. another option is fiddler – Zohaib Aslam Dec 01 '14 at 17:18

1 Answers1

7

Request.UserAgent is just value of "user agent" header in HTTP request. Browser will automatically send it with all requests (including AJAX), no-browser clients generally will not include such header.

If your "client" is not browser it needs to add the header with appropriate values itself.

Sample if using HttpWebRequest

var request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
request.UserAgent="My custom user agent string";
var response = (HttpWebResponse)myHttpWebRequest.GetResponse();
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179