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
#if !NET45
using Prow.Cache;
using Microsoft.AspNetCore.Http;
#if NETSTANDARD2_0
using Newtonsoft.Json;
#else
using System.Text.Json;
#endif
 
namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// CacheManagerCorsHandler 中间件扩展类,负责解析 /CacheList.axd 请求
    /// </summary>
    public static class CacheManagerExtensions
    {
        /// <summary>
        /// 增加CacheManager跨站点管理中间件
        /// </summary>
        /// <param name="builder"></param>
        public static IApplicationBuilder UseCacheManager(this IApplicationBuilder builder)
        {
            return builder.MapWhen(context => context.Request.Path == "/CacheList.axd", app => app.Run(async context =>
            {
                var buffer = "[]";
                if (context.User.Identity.IsAuthenticated)
                {
                    var cacheKey = context.Request.Query.ContainsKey("cacheKey") ? context.Request.Query["cacheKey"].ToString() : string.Empty;
                    if (cacheKey == "*")
                    {
                        CacheManager.Clear();
                    }
                    else
                    {
                        // cacheKey = "Key1|Key2|Key3"
                        if (!string.IsNullOrEmpty(cacheKey)) CacheManager.Clear(cacheKey.Split('|'));
#if NETSTANDARD2_0
                        buffer = JsonConvert.SerializeObject(CacheManager.ToList());
#else
                        buffer = JsonSerializer.Serialize(CacheManager.ToList());
#endif
                    }
                }
                context.Response.Headers.Add("Content-Type", new Microsoft.Extensions.Primitives.StringValues("application/json; charset=utf-8"));
                await context.Response.WriteAsync(buffer);
            }));
        }
    }
}
#endif