即使服务器返回304,Chrome也会在网络中显示200正常状态

时间:2020-05-04 04:02:04

标签: google-chrome caching .net-core asp.net-web-api2 http-status-code-304

我正在构建前端和后端应用程序。 在请求中使用If if match header时,我的服务器返回304状态,但是chrome始终显示200状态。 Firefox和IE可以很好地实现相同的实现。 所有标题均正确放置 我已将cache-control添加到max-age 0,并始终进行重新验证。 但是chrome成功显示了缓存的数据,但是为什么我在网络中看不到304状态 以下是chrome和Firefox网络面板中的图片

Image from chrome Image from Firefox

我的后端内置于.net核心中,我使用动作过滤器属性返回ETag和304状态,下面是代码

public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){ var isRequestMethodGet = context.HttpContext.Request.Method == "GET";
    bool isModified = false;
    string authToken = "";
        var path = context.HttpContext.Request.Path.ToString() + context.HttpContext.Request.QueryString.ToString();
        if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
        {
            authToken = context.HttpContext.Request.Headers["Authorization"];
        }

        var etag = GetETag(path, authToken);
        if (isRequestMethodGet)
        {
            var myId = context.HttpContext.Request.Headers["myId"].ToString();
            var value = await distributedCacheRepository.GetCachedItem($"{redisPrefix}-{myId}");
            if (value != null)
            {
                if (context.HttpContext.Request.Headers.Keys.Contains("If-None-Match") && context.HttpContext.Request.Headers["If-None-Match"].ToString() == etag)
                {
                    isModified = true;
                    context.HttpContext.Response.StatusCode = 304;
                    context.Result = new StatusCodeResult((int)HttpStatusCode.NotModified);
                }
            }
            else
            {
                await distributedCacheRepository.InsertKeyValueAsync($"{redisPrefix}-{myId}", myId);
            }
        }

        if(!isRequestMethodGet || !isModified)
        {
            await next();
        }

       context.HttpContext.Response.Headers.Add("cache-control", new[] { "no-transform", "must-revalidate", "max-age=0" });
       context.HttpContext.Response.Headers.Add("vary", new[] { "Accept", "Accept-Encoding", "Authorization", "Cookie" });           
       context.HttpContext.Response.Headers.Add("ETag", new[] { etag }); }

1 个答案:

答案 0 :(得分:0)

您是否正在将请求发送到其他端口/域?我遇到了与您相同的问题,服务器返回304(通过邮递员检查),但chrome显示为200。
这是我找出原因的方法:

  1. 在我昂首阔步的文档中,返回了304(请求从localhost:8083发送到localhost:8083)
  2. 在我的应用程序中,返回了相同的请求,但返回了200(请求从localhost:4300发送到localhost:8083)
  3. 所以我将我的应用程序请求代理到同一域(请求从localhost:4300发送到localhost:4300,然后代理到localhost:8083)
  4. 我得到了预期的304