Creating an HttpBrowserCapabilitiesBase from a UserAgent String

Thus, the HttpRequestBase class has a Browser property that returns an HttpBrowserCapabilitiesBase . We are currently using this property in some of our MVC infrastructure code to get things like browser name and number (for output to logs).

We also have an api that uses ServiceStack , and I would like to be able to connect it to our existing infrastructure. The only thing missing is to parse the name and version of the browser from the UserAgent header (which I have thanks to IHttpRequest.UserAgent), but you need a way to parse it.

My question is: is it possible to create an HttpBrowserCapabilitiesBase using only the UserAgent string? The only subtype that I see in msdn is HttpBrowserCapabilitiesWrapper , whose only ctor is another HttpBrowserCapabilitiesBase.

I thought this class probably exclusively parses the UserAgent string, so why not ctor (string)? Is there a subtype, factory, or static method that I don't see that can do this?

As a rule, I just do it for laziness - I donโ€™t want to write / find another UserAgent parser when I know .Net has such an opportunity that they just hide it.

+7
source share
1 answer

I just had to do it myself. Here is what I have tried. It was decompiled from System.Web , but still depends on this library. I am still checking this, but maybe this helps you:

 public class BrowserCapabilities { public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollection headers, string userAgent) { var factory = new BrowserCapabilitiesFactory(); var browserCaps = new HttpBrowserCapabilities(); var hashtable = new Hashtable(180, StringComparer.OrdinalIgnoreCase); hashtable[string.Empty] = userAgent; browserCaps.Capabilities = hashtable; factory.ConfigureBrowserCapabilities(headers, browserCaps); factory.ConfigureCustomCapabilities(headers, browserCaps); return browserCaps; } } 

To check:

 var features = BrowserCapabilities.GetHttpBrowserCapabilities(null, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"); Console.WriteLine(features.Browser); 
+9
source