I'm trying to detect the current web browser within one of my Api Controllers in my program using MVC4. Everywhere I look people say to use Request.Browser
, however I can't get that to work. Any suggestions or is there something I'm overlooking?
Asked
Active
Viewed 2.3k times
18

Smoore
- 732
- 2
- 10
- 27
-
3Request in an APIController is an HttpRequestMessage vs the HttpRequest that contains the browser information. To get the browser capabilities, just use `HttpBrowserCapabilities bc = HttpContext.Current.Request.Browser;` – Mark Seefeldt Jan 15 '14 at 16:45
2 Answers
24
You can use the HttpBrowserCapabilities in System.Web like this
var userAgent = HttpContext.Current.Request.UserAgent;
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
//Set User browser Properties
BrowserBrand = userBrowser.Browser;
BrowserVersion = userBrowser.Version;
This relies on browscap.ini in Windows/System32/inetsrv/ or Windows/SysWOW64/inetsrv for definitions.
This article may also help - http://stephenwalther.com/archive/2010/03/05/use-asp-net-4-browser-definitions-with-asp-net-3-5
-
5If you use HttpContext.Current.Request.UserAgent, why not use HttpContext.Current.Request.Browser? – Peter Hedberg Feb 04 '14 at 08:22
-
1@PeterHedberg Good question, but I tried your solution and found that UserAgent contains all supported browsers and OS as well. But if I tried with MS Edge, the HttpContext.Current.Request.Browser show me that I am using Chrome. – Kay Nov 01 '18 at 04:22
-
@Kramer MS Edge is on Chromium now. https://blogs.windows.com/windowsexperience/2018/12/06/microsoft-edge-making-the-web-better-through-more-open-source-collaboration/ – Dhanil Dinesan Jul 24 '19 at 03:49
10
You could do something like following too from within the Web API's action:
System.Net.Http.HttpRequestMessage currentRequest = this.Request;
System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> userAgentHeader = currentRequest.Headers.UserAgent;

Kiran
- 56,921
- 15
- 176
- 161