在Angular和C#中遇到CORS问题时,尽管进行了CORS配置,但POST、PUT、DELETE等请求无法正常工作,可能需要采取以下解决方法。
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
然后,在Configure方法中的app.UseCors()添加以下代码:
app.UseCors("AllowAllOrigins");
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
...
})
export class AppModule { }
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class YourService {
constructor(private http: HttpClient) {}
create(data: any): Observable {
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post('your-api-url', data, options);
}
}
请将'your-api-url'替换为实际的API地址。
app.Use(async (context, next) =>
{
if (context.Request.Method == "OPTIONS")
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
context.Response.Headers.Add("Access-Control-Max-Age", "86400");
context.Response.StatusCode = 200;
}
await next();
});
这将处理来自Angular的预检请求(OPTIONS请求)。
这些解决方法应该能够解决Angular和C#中的CORS问题,确保POST、PUT、DELETE等请求正常工作。