【问题标题】:.Net-Core get HttpBrowserCapabilities from httpContext.Net-Core 从 httpContext 获取 HttpBrowserCapabilities
【发布时间】:2017-10-09 07:31:57
【问题描述】:

我想在 .net-core 中使用 HttpBrowserCapabilities。我尝试了以下方式:

var userAgent = httpContext.Request.Headers["user-agent"];
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
var mobileString = userBrowser.IsMobileDevice ? "(mobil)" : string.Empty;
var browserString = $"{userBrowser.Browser} version {userBrowser.Version} {mobileString} OS: {userBrowser.Platform}";

但是会抛出 InvalidCastException。我怎样才能让这段代码重新调整正确的值?

【问题讨论】:

    标签: asp.net-core httpcontext


    【解决方案1】:

    知道了!

    userAgent 的类型为 Microsoft.Extensions.Primitives.StringValues。 但是HttpBrowserCapabilities 需要一个字符串作为输入参数。

    因此我必须检查 userAgent 是否包含一个值 (userAgent.Any()) 并使用以下代码

    var userBrowser = new HttpBrowserCapabilities {Capabilities = new Hashtable {{string.Empty, userAgent.First()}}};
    

    【讨论】:

    • 而不是ToArray()[0]First() 不起作用?
    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 2020-05-08
    • 1970-01-01
    • 2022-11-15
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    相关资源
    最近更新 更多