所以 HttpRequestBase 类有一个浏览器属性,返回 HttpBrowserCapabilitiesBase 。我们目前在一些MVC基础设施代码中使用此属性来获取浏览器名称和版本号(输出到日志)。
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).
我们还有一个使用 ServiceStack 的API,我想能够将其挂钩到我们现有的基础设施中。唯一缺少的是能够解析UserAgent标题中的浏览器名称和版本(我感谢IHttpRequest.UserAgent),但需要一种方法来解析它。
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.
我的问题 - 是否可以仅使用UserAgent字符串以某种方式创建HttpBrowserCapabilitiesBase?我在msdn上看到的唯一可用子类型是 HttpBrowserCapabilitiesWrapper ,其唯一的ctor是另一个HttpBrowserCapabilitiesBase。
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.
我原以为这个类可能只是解析UserAgent字符串,所以为什么不存在ctor(字符串)?是否有一个我没有看到的子类型,工厂或静态方法可以实现这个目标?
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?
一般来说我只是为了懒惰而这样做 - 我不想写/找到另一个UserAgent解析器,我知道.Net有这个功能,他们只是隐藏它。
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.
推荐答案我必须自己做。这是我尝试过的。它是从 System.Web 反编译的,但仍然依赖于该库。我还在测试它,但也许它可以帮到你:
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; } }测试:
var features = BrowserCapabilities.GetHttpBrowserCapabilities(null, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"); Console.WriteLine(features.Browser);更多推荐
从UserAgent字符串创建HttpBrowserCapabilitiesBase
发布评论