我目前正在將一個專案從 .Net Framework 轉換為 .Net 5。
當我點擊新的 .Net 5 專案中的端點之一時,出現以下例外。
System.InvalidOperationException: '誤用的標頭名稱,'Access-Control-Allow-Origin'。確保請求標頭與 HttpRequestMessage 一起使用,回應標頭與 HttpResponseMessage 一起使用,內容標頭與 HttpContent 物件一起使用。
端點看起來像這樣,在我將“Access-Control-Allow-Origin”添加到回應內容標頭的行上拋出例外。
[HttpGet]
[Route("api/Recommendations/GetRecommendations/{id}/{count}")]
public HttpResponseMessage GetRecommendations(int id, int count)
{
var response = new HttpResponseMessage();
response.Content = new StringContent(_recommendationsAPIService.GetRecommendations(id, count));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Content.Headers.Add("Access-Control-Allow-Origin", "*");
response.Content.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Referer, Authorization,Sec-Fetch-Mode,User-Agent");
return response;
}
如何修復此例外?
我不熟悉最初撰寫該專案的人,所以有什么理由將這些標題添加到回應中嗎?
uj5u.com熱心網友回復:
您不應使用該Content.Headers屬性添加此類標題。檢查檔案:這里
表示 RFC 2616 中定義的內容標頭的集合。
所以它應該用于非常特定的標題。
另外兩件事:
1st - 您在內容上添加標題。該訊息很清楚,您應該將其添加到回應中。在此處查看:在 ApiController 中添加自定義回應標頭以了解將其添加到回應中的方式
response.Headers.Add("X-Students-Total-Count", students.Count());
第二 - CORs 是您需要在全球范圍內應用的東西!請點擊這里了解如何配置你的API來做到這一點。
TLDR;
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Some code here
app.UseCors(MyAllowSpecificOrigins);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/345092.html
上一篇:帶有多行文本的WinformDatagridview按鈕列按鈕
下一篇:為什么VisualStudioNugetPackageManager中的“版本”列在.NETFramework專案中顯示為空白?
