![](/img/trans.png)
[英]Is it possible to add 2 distinct Content-Disposition headers in the following way
[英]Im not able to access Response.Headers(“Content-Disposition”) on client even after enable CORS
我正在嘗試檢索在后端(Asp.net Core 2.2)中生成的 excel 文件的文件名,正如您在 c# 代碼中看到的那樣,文件名是在 Z099FB995346F031C743F6E 的響應中檢索到的,但客戶端無法訪問到 header '內容處置'
正如您在下面的打印中看到的那樣,盡管標頭中不存在 Content disposition,但它存在於 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
};
})
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 header。
您還可以在返回響應之前使用類似的內容:
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Response.Headers.Add("Content-Disposition", YOUR_VALUE);
這樣,每個端點都可以暴露一個自定義 header,而無需更新 Startup.cs。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.