zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Text.RegularExpressions;
 
namespace Microsoft.AspNetCore.Http
{
    /// <summary>
    /// Reqeust 扩展操作类
    /// </summary>
    public static class RequestExtensions
    {
        private static readonly Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
 
        /// <summary>
        /// 判断是否为移动设备
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsMobileDevice(this HttpRequest request)
        {
            var userAgent = request.UserAgent();
            return b.IsMatch(userAgent);
        }
 
        /// <summary>
        /// 判断是否为 IPad
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsIPad(this HttpRequest request)
        {
            var userAgent = request.UserAgent();
            return userAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) > 0;
        }
 
        /// <summary>
        /// 获得请求 UserAgent 字符串 读取 Header["User-Agent"]
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string UserAgent(this HttpRequest request)
        {
            return request.Headers["User-Agent"];
        }
 
        /// <summary>
        /// 获得请求绝对路径
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string AbsoluteUrl(this HttpRequest request)
        {
            return $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
        }
    }
}