如何获取客户端的浏览器信息?



如何在 asp.net 核心 3.0.1 中获取客户端的浏览器信息,I 尝试使用此代码,但是,它向我返回了用户的完整列表 浏览器,但是,我需要使用它的用户的浏览器。

我使用的代码:

var userAgent = Request.Headers["User-Agent"].ToString();

我也尝试了这段代码,但是,它给了我错误:

UserAgent.UserAgent ua = new UserAgent.UserAgent(userAgent);

我搜索了很多链接,但是,我没有找到我需要的东西,而且,这是我搜索的一些链接:

  1. https://code.msdn.microsoft.com/How-to-get-OS-and-browser-c007dbf7
  2. 如何在 Asp.net 核心中获取用户浏览器名称(用户代理(?
  3. https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.useragent?view=netframework-4.8
  4. https://www.c-sharpcorner.com/forums/how-to-get-current-browser-details-in-asp-net-core

有没有办法获取客户端使用 Core 3.0.1 从中运行应用程序的浏览器名称和版本Asp.Net?

您可以安装Wangkanai.Detection软件包。完整的文档可以在这里找到:https://github.com/wangkanai/Detection

检测库的安装现在只需一个软件包即可完成 参考点。

PM> install-package Wangkanai.Detection -pre

虽然如果您只需要该特定解析程序,仍然可以安装单个包。

PM> install-package Wangkanai.Detection.Device -pre  
PM> install-package Wangkanai.Detection.Browser -pre  
PM> install-package Wangkanai.Detection.Engine -pre   //concept
PM> install-package Wangkanai.Detection.Platform -pre //concept
PM> install-package Wangkanai.Detection.Crawler -pre  

安装Responsive库将引入所有依赖项包(这将包括Wangkanai.Detection.Device(。

PM> install-package Wangkanai.Responsive -pre

我认为以下内容对您来说应该足够了:

install-package Wangkanai.Detection -pre 
install-package Wangkanai.Detection.Browser -pre

然后,您需要通过在ConfigureServices方法中添加检测服务来配置Startup.cs

public void ConfigureServices(IServiceCollection services)
{
// Add detection services container and device resolver service.
services.AddDetection();
services.AddDetectionCore().AddBrowser();
// Add framework services.
services.AddMvc();
}

最后在你的Controller,做这样的事情:

public class HomeController : Controller
{
private readonly IDetection _detection;
public HomeController(IDetection detection)
{
_detection = detection;
}
public IActionResult Index()
{
string browser_information = _detection.Browser.Type.ToString() +
_detection.Browser.Version;
//...
}
} 

您可以使用此 nuget 包,该包旨在提供可靠的语义分析。

举一个简单的例子,我将使用单例而不是依赖注入:

public static class YauaaSingleton
{
private static UserAgentAnalyzer.UserAgentAnalyzerBuilder Builder { get; }
private static readonly Lazy<UserAgentAnalyzer> analyzer = new Lazy<UserAgentAnalyzer> (() => Builder.Build());
public static UserAgentAnalyzer Analyzer
{
get
{
return analyzer.Value;
}
}
static YauaaSingleton()
{
Builder = UserAgentAnalyzer.NewBuilder();
Builder.DropTests();
Builder.DelayInitialization();
Builder.WithCache(100);
Builder.HideMatcherLoadStats();
Builder.WithAllFields();
}
}

然后在控制器中:

var userAgentString  = this.HttpContext?.Request?.Headers?.FirstOrDefault(s => s.Key.ToLower() == "user-agent").Value;
var ua = YauaaSingleton.Analyzer.Parse(userAgentString);
var browserNameField = ua.Get(DefaultUserAgentFields.AGENT_NAME);
var browserVersionField = ua.Get(DefaultUserAgentFields.AGENT_VERSION);
Debug.WriteLine(browserNameField.GetValue());
Debug.WriteLine(browserVersionField.GetValue());

对于工作示例,您可以在此处找到完整的 asp.net 核心项目

最新更新