如何在Asp.net Core中获取用户浏览器名称(用户代理)?

ead*_*dam 73 asp.net-core-mvc asp.net-core

能告诉我如何获取客户端在MVC 6,asp.net 5中使用的浏览器的名称吗?

ead*_*dam 116

我觉得这很简单.得到了答案Request.Headers["User-Agent"].ToString().

  • 有些人可能更喜欢`Request.Headers [HeaderNames.UserAgent]`作为避免字符串文字(可能没有在Core 1.0中工作,不确定) (22认同)
  • 抓一点.它只是因为某种原因返回"".万岁一致...... (10认同)
  • 如果请求没有User-Agent,请注意这将导致KeyNotFoundException!一定要先使用.ContainsKey来检查! (7认同)
  • 这将所有浏览器名称都返回给我 (5认同)
  • @kobosh`Request.Headers [“ User-Agent”]。ToString()` (2认同)
  • @WillDean此常量位于Microsoft.Net.Http.Headers命名空间中。 (2认同)
  • 这返回了浏览器的所有名称,但只需要客户端浏览器详细信息 (2认同)

Ane*_*han 11

对我来说,没有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);
Run Code Online (Sandbox Code Playgroud)

使用上面的代码后,可以通过使用userAgent获取浏览器详细信息,c.UserAgent.Family 还可以像c.OS.Family;

  • 这不是所有浏览器名称的列表,这是浏览器设置为用户代理的内容。UAParser 知道如何获取所有这些名称并确定实际的浏览器和操作系统是什么。 (6认同)
  • 正是我需要的! (2认同)

Sar*_*nai 6

我已经开发了一个库来扩展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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)