gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:24:00 26 4
gpt4 key购买 nike

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

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

response.headers 的日志
enter image description here

XHR
t

我已经在后端启用了 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
};
})

Startup.cs(配置方法)
app.UseAuthentication();
app.UseCors(CorsAllowAllOrigins);
app.UseMvc();

Controller
[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;
}
}

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

容器.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);
});
}

报表服务.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' });
}

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.

最佳答案

您的服务器需要使用 WithExposedHeaders 将 header 作为其 CORS 配置的一部分公开。 .下面是一个例子:

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

这设置了 Access-Control-Expose-Headers标题。

关于c# - 即使在启用 CORS 后,我也无法访问客户端上的 Response.Headers ("Content-Disposition"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com