即使启用 CORS,我也无法访问客户端上的 Response.Headers("Content-Disposition")

Pug*_*ore 3 c# asp.net-web-api typescript asp.net-core angular

我试图检索在后端(Asp.net Core 2.2)中生成的 excel 文件的文件名,正如您在 c# 代码中看到的,文件名在响应的标头中检索,但从客户端我无法访问到标题“内容处理”

正如您在打印波纹管中看到的,尽管内容处置不存在于标题中,但它存在于 XHR 响应标题中

response.headers 的日志 在此处输入图片说明

XHR 吨

我已经在后端启用了 de CORS 策略,如下所示:

Startup.cs(ConfigureServices 方法)

services
    .AddCors(options =>
    {
        options.AddPolicy(CorsAllowAllOrigins,
            builder => builder.WithOrigins("*").WithHeaders("*").WithMethods("*"));
    })
    .AddMvc(options =>
    {
        options.Filters.Add(new AuthorizeFilter(authorizationPolicy));
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        var key = Encoding.ASCII.GetBytes(jwtSecurityOptions.SecretKey);

        options.Audience = jwtSecurityOptions.Audience;
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    })
Run Code Online (Sandbox Code Playgroud)

Startup.cs(配置方法)

app.UseAuthentication();
app.UseCors(CorsAllowAllOrigins);
app.UseMvc();
Run Code Online (Sandbox Code Playgroud)

控制器

[HttpGet("{reportResultId}/exportExcelFile")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesErrorResponseType(typeof(void))]
[Authorize(Policy = nameof(RoleType.N1))]
public ActionResult ExportExcelFile(int reportResultId, [FromQuery]bool matchedRows, [FromQuery]ExportExcelType exportExcelType)
{
    var authenticatedUser = Request.GetAuthenticatedUser();
    var result = _reconciliationResultService.GetDataForExportExcelFile(reportResultId, matchedRows,authenticatedUser.UserName ,exportExcelType, authenticatedUser.UserName, authenticatedUser.Id);

    if (result != null)
    {
        MemoryStream memoryStream = new MemoryStream(result.WorkbookContent);
        var contentType = new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        var fileStreamResult = new FileStreamResult(memoryStream, contentType)
        {
            FileDownloadName = result.FileName
        };

        fileStreamResult.FileDownloadName=result.FileName;

        return fileStreamResult;
    }
    else
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

- - - - - - - 客户 - - - - - - - - - - -

容器.ts

exportExcelFile(matchedRows: string) {
    this._reportService.exportExcelFile(matchedRows, this.reportInfo.id, this.exportExcelType).subscribe((response) => {
        var filename = response.headers.get("Content-Disposition").split('=')[1]; //An error is thrown in this line because response.headers.get("Content-Disposition") is always null
        filename = filename.replace(/"/g, "")
        const blob = new Blob([response.body],
            { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        const file = new File([blob], filename,
            { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        this.exportingExcelFile = false;
        this.ready = true;
        saveAs(file);
    });
}
Run Code Online (Sandbox Code Playgroud)

报表服务.ts

exportExcelFile(matchedRows: string, reportInfoId: number, exportExcelType:ExportExcelType): Observable<any> {
    const url = `${environment.apiUrls.v1}/reconciliationResult/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}&exportExcelType=${exportExcelType}`;
    return this.http.get(url, { observe: 'response', responseType: 'blob' });
}
Run Code Online (Sandbox Code Playgroud)

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppRoutingModule } from './app.routing.module';
import { ReportModule } from './report/report.module';

import { AppComponent } from './app.component';
import { TopNavComponent } from './layout/topnav.component';
import { SideBarComponent } from './layout/sidebar.component';
import { DatePipe } from '@angular/common';
import { DynamicDialogModule } from 'primeng/dynamicdialog';
import { SharedModule } from './core/shared.module';
import { JwtInterceptor } from './core/_helpers/jwt.interceptor';
import { ErrorInterceptor } from './core/_helpers/error.interceptor';
import { LoginRoutingModule } from './login/login-routing.module';
import { LogingModule } from './login/login.module';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    SharedModule,
    ReportModule,
    AppRoutingModule,
    DynamicDialogModule,
    LogingModule,
    LoginRoutingModule
  ],
  declarations: [
    AppComponent,
    TopNavComponent,
    SideBarComponent
  ],
  providers: [
    DatePipe,
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
     { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }
```

Note: I'm implementing JWT. I don't know if it can have any impact on the headers.
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 8

你的服务器需要露出头作为其CORS配置的一部分,使用WithExposedHeaders。下面是一个例子:

services
    .AddCors(options =>
    {
        options.AddPolicy(CorsAllowAllOrigins, builder => 
            builder.WithOrigins("*")
                   .WithHeaders("*")
                   .WithMethods("*")
                   .WithExposedHeaders("Content-Disposition"));
    });
Run Code Online (Sandbox Code Playgroud)

这将设置Access-Control-Expose-Headers标头。

  • `WithHeaders` 是关于客户端可以发送的标头(即请求标头),而 `WithExposedHeaders` 是关于客户端可以接收的标头(即响应标头)。 (3认同)