So the HttpRequestBase class has a Browser property that returns a HttpBrowserCapabilitiesBase. We currently use this property in some of our MVC infrastructure code to get things like the Browser name and version number (for output to logs).
We also have an api that uses ServiceStack, and I would like to be able to hook this into our existing infrastructure. The only thing missing is being able to parse the browser name and version out of the UserAgent header (which I have thanks to the IHttpRequest.UserAgent), but need a way to parse it.
My question - is it possible to create a HttpBrowserCapabilitiesBase somehow with just a UserAgent string? The only available subtype I see on msdn is HttpBrowserCapabilitiesWrapper, whose sole ctor is another HttpBrowserCapabilitiesBase.
I was thinking that this class probably solely parses the UserAgent string anyways, so why isn't there a ctor(string)?? Is there a subtype, factory or static method I am not seeing that can accomplish this?
Generally I am just doing this for laziness - I don't want to write/find another UserAgent parser when I know .Net has that capability they are just hiding it.
I just had to do this myself. Here's what I tried. It's decompiled from System.Web
, but is still dependent on that library. I'm still testing it, but maybe it 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 test:
var features = BrowserCapabilities.GetHttpBrowserCapabilities(null,
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
Console.WriteLine(features.Browser);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With