Answers:
我认为这很容易。得到答案Request.Headers["User-Agent"].ToString()
谢谢
Request.Headers["User-Agent"].ToString()
Request.Headers[HeaderNames.UserAgent]
避免使用字符串文字(不确定在Core 1.0中可能无法使用)
对我来说,没有Request.Headers["User-Agent"].ToString()
帮助返回所有浏览器的名称,因此在解决方案后找到了它。
安装了ua-parse。在控制器中using UAParser;
var userAgent = httpContext.Request.Headers["User-Agent"];
string uaString = Convert.ToString(userAgent[0]);
var uaParser = Parser.GetDefault();
ClientInfo c = uaParser.Parse(uaString);
使用上面的代码后,可以通过使用从userAgent获取浏览器详细c.UserAgent.Family
信息。c.OS.Family;
userAgent = Request.Headers["User-Agent"];
https://code.msdn.microsoft.com/How-to-get-OS-and-browser-c007dbf7(链接未激活)进行了4.8版
https://docs.microsoft.com/zh-cn/dotnet/api/system.web.httprequest.useragent?view=netframework-4.8
我已经开发了一个库来扩展ASP.NET Core,以支持Wangkanai.Detection中的 Web客户端浏览器信息检测。这应该可以让您标识浏览器名称。
namespace Wangkanai.Detection
{
/// <summary>
/// Provides the APIs for query client access device.
/// </summary>
public class DetectionService : IDetectionService
{
public HttpContext Context { get; }
public IUserAgent UserAgent { get; }
public DetectionService(IServiceProvider services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
this.Context = services.GetRequiredService<IHttpContextAccessor>().HttpContext;
this.UserAgent = CreateUserAgent(this.Context);
}
private IUserAgent CreateUserAgent(HttpContext context)
{
if (context == null) throw new ArgumentNullException(nameof(Context));
return new UserAgent(Context.Request.Headers["User-Agent"].FirstOrDefault());
}
}
}
DeviceResolver.cs
找出它是手机,台式机还是台式机,但是看不到类似的代码来提取用户代理标头的详细信息。
安装此.nuget软件包
创建一个这样的类:
public static class YauaaSingleton
{
private static UserAgentAnalyzer.UserAgentAnalyzerBuilder Builder { get; }
private static UserAgentAnalyzer analyzer = null;
public static UserAgentAnalyzer Analyzer
{
get
{
if (analyzer == null)
{
analyzer = Builder.Build();
}
return analyzer;
}
}
static YauaaSingleton()
{
Builder = UserAgentAnalyzer.NewBuilder();
Builder.DropTests();
Builder.DelayInitialization();
Builder.WithCache(100);
Builder.HideMatcherLoadStats();
Builder.WithAllFields();
}
}
在控制器中,您可以从http标头中读取用户代理:
string userAgent = Request.Headers?.FirstOrDefault(s => s.Key.ToLower() == "user-agent").Value;
然后,您可以解析用户代理:
var ua = YauaaSingleton.Analyzer.Parse(userAgent );
var browserName = ua.Get(UserAgent.AGENT_NAME).GetValue();
您还可以获得置信度(越高越好):
var confidence = ua.Get(UserAgent.AGENT_NAME).GetConfidence();