繁体   English   中英

使用 http 拦截器在 Angular 应用程序中读取 asp.net 核心 http 响应标头

[英]Read asp.net core http response header in angular app with http interceptor

我尝试通过在 http 标头中将当前服务器版本发送到客户端来进行简单的 appversion 检查,如果有更新的版本,它应该通知用户重新加载。 我认为这将是一项简单的任务,但我的角度拦截器没有得到我的新响应头由 asp.net 核心发送。 我使用 .Net6 和 Angular 13。

启动.cs

app.Use(async (context, next) =>
{
   context.Response.Headers.Add("X-AppVersion", Assembly.GetEntryAssembly()!.GetName().Version!.ToString());
   await next();
});

app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    var headers = context.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue
                    {
                        NoCache = true,
                        NoStore = true,
                        MustRevalidate = true,
                        MaxAge = TimeSpan.Zero
                    };
                    // Not sure about this one
                    headers.Append("X-AppVersion", Assembly.GetEntryAssembly()!.GetName().Version!.ToString());
                }
            };
        });

角拦截器

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   const reqWithCredentials = req.clone({ withCredentials: true });
   return next.handle(reqWithCredentials).pipe(
    map(resp => {
      if (resp instanceof HttpResponse) {
        if (resp.headers.get('x-appversion')) {
          console.log(resp.headers.get('x-appversion'));
        } else {
          console.log(null); // I always get null
        }
        return resp;
      }
    })
  )
}

我必须在 app.UseEndpoints() 之前移动我的 app.Use() 中间件配置才能使其正常工作。

相关: https ://github.com/dotnet/aspnetcore/issues/18768

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM