C# ETagCacheMiddleware

2021-01-18 22:16

阅读:543

标签:private   await   项目   sci   readonly   red   only   redis   tty   

 

记录下之前项目写的etag。

 

 public class ETagCacheMiddleware
    {
        private readonly RequestDelegate _next;

        public ETagCacheMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var originalResponseStream = context.Response.Body;
            var etag = "";
            if (context.Request.Headers.ContainsKey("etag"))
            {
                etag = context.Request.Headers["etag"].ToString();
                var response = await _redisCacheClient.Value.GetOrDefaultstring>(etag);

                if (response == null)
                {
                    using (var ms = new MemoryStream())
                    {
                        context.Response.Body = ms;
                        context.Response.Headers.Add("etag", etag);
                        await _next(context);

                        ms.Seek(0,SeekOrigin.Begin);

                        var responseReader = new StreamReader(ms);
                        var responseContent = responseReader.ReadToEnd();

                        ms.Seek(0, SeekOrigin.Begin);

                        await ms.CopyToAsync(originalResponseStream);
                        context.Response.Body = originalResponseStream;
              
              //可根据具体需求操作已获得的etag和请求返回内容responseContent
} }
else { //返回response context.Response.Headers.Add("etag",etag); context.Response.ContentType = "application/json"; using (var ms = new MemoryStream()) { var orgBodyStream = context.Response.Body; context.Response.Body = ms; ms.Seek(0, SeekOrigin.Begin); byte[] responseArray = Encoding.ASCII.GetBytes(response); ms.Write(responseArray, 0, responseArray.Length); ms.Seek(0, SeekOrigin.Begin); await ms.CopyToAsync(orgBodyStream); context.Response.Body = orgBodyStream; } } } else { await _next(context); } } }

 

C# ETagCacheMiddleware

标签:private   await   项目   sci   readonly   red   only   redis   tty   

原文地址:https://www.cnblogs.com/yuerduo/p/12170639.html


评论


亲,登录后才可以留言!