[英]Enable preflight CORS between C# and Angular
我正在嘗試使 CORS 為需要預檢檢查的請求工作。 在這種情況下,我使用額外的 header 向后端發出 POST 請求。
Angular:
let myHeaders = new HttpHeaders();
myHeaders = myHeaders.append('Content-Type', 'application/json');
return this.http.post<UserOrder>(`${this.apiURL}/Order/PlaceOrder`, JSON.stringify(payload), {headers : myHeaders}); //email);
C# API:
[HttpPost("PlaceOrder")]
public GenericResponse PlaceOrder(UserOrderInsertModel userOrder)
{
return _orderProvider.PlaceOrder(new UserOrder());
}
由於預檢檢查,它首先發出一個 OPTIONS 請求。 當我沒有在后端定義單獨的選項端點時,我得到一個 405 Method Not Allowed。 這讓我覺得我需要一個單獨的 options-endpoint 在我的后端在 post-endpoint 之上。
[HttpOptions("PlaceOrder")]
public ActionResult PlaceOrderOptions(UserOrderInsertModel userOrder)
{
return Ok();
}
添加后,我遇到了 415 Unsupported Media Type(在選項調用中)。 這可能是因為 HttpOptions 請求不支持 Content-Type header。
我覺得根本不需要額外的選項端點。 我目前使用的CORS-middleware如下:
httpContext.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");
httpContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
httpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
額外信息:CORS 通常已經工作了。 帶有 GET 請求和 Access-Control-Allow-Origin header 的跨站點腳本運行良好。 只是我無法讓 POST/OPTIONS 組合工作。
編輯:在 Startup.cs 我首先嘗試使用 app.UseCors() 如下:
app.UseCors();
options => options.WithOrigins("http://localhost").AllowAnyMethod()
);
不幸的是,這不起作用,所以我求助於如上所述插入中間件。
任何幫助將不勝感激!
確保在 UseEndpoints() 之前調用 UseCors()。 另一個提示:如果您有憑據,則通配符不會按預期工作。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
好的,非常感謝大家。 問題很可能出在我使用的中間件上。 這是我添加的一種解決方法,因為 UseCors() 最初不起作用。 這可能是因為我最初沒有使用 app.AddCors()。 如果沒有自定義中間件,一切都會變得容易得多!
快速查看文檔將澄清一些事情。 我在下面分享一些摘錄
由於預檢檢查,它首先發出一個 OPTIONS 請求。 當我沒有在后端定義單獨的選項端點時,我得到一個 405 Method Not Allowed。 這讓我覺得我需要一個單獨的 options-endpoint 在我的后端在 post-endpoint 之上。
對於某些 CORS 請求,瀏覽器會在發出實際請求之前發送一個額外的 OPTIONS 請求。 該請求稱為預檢請求。 如果以下所有條件都為真,瀏覽器可以跳過預檢請求
我覺得根本不需要額外的選項端點。
除了使用帶有端點路由的 CORS 外,ASPNET Core 應該在啟動時啟用內核時響應適當的預檢請求。
當應用 CORS 策略時:
ASP.NET 內核響應預檢選項請求。
使用 RequireCors 在每個端點上啟用 CORS 目前不支持自動預檢請求。
在配置服務中
public void ConfigureServices(IServiceCollection services) { . //other codes . services.AddCors(options => { options.AddDefaultPolicy( builder => //check corsbuilder for additonal config { builder.WithOrigins("http://example.com", "http://www.contoso.com; }); }); . //other codes . }
並在配置方法中
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { . //Other codes . app.UseCors(); . //Other codes . }
此處為 3.0 https 的完整文檔://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.0#ecors
啟用 Cors 並確保 AllowAnyHeader 和 AllowAnyMethod Using.Net Core
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.WithOrigins(Configuration.GetValue<string>("JwtConfig:corsWhiteListUrl"))
.AllowAnyHeader()
.AllowAnyMethod();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.