我以为我可以访问所有来源,但仍然出现此错误。
CORS策略已阻止从来源“ http:// localhost:4200”访问“ localhost:60248 / api / page / 1”处的XMLHttpRequest:仅协议方案支持跨来源请求:http,data,chrome,chrome -扩展名,https。
UPDATE在添加建议的代码更改后,错误已更改。现在如下:
通过CORS策略已阻止从来源“ http:// localhost:4200”访问“ http:// localhost:60248 / api / page / 1”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:重定向不允许进行预检请求。
在Startup.cs中,我有以下内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.WithMethods("PUT", "DELETE", "GET");
});
});
在我的控制器中,我有:
[Route("api/[controller]")]
[ApiController]
public class PageController : ControllerBase
{
...
[EnableCors("AllowAll")]
[HttpGet("{id:int}")]
public async Task<IActionResult> GetPageData(int id)
{
...
这是调用端点的Angular服务:
export class PageContentService {
constructor(private http: HttpClient) { }
getContent(id: number): Observable<PageContent> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
const httpOptions = {
headers: headers
}
return this.http.get<PageContent>(`http://localhost:60248/api/page/${id}`, httpOptions);
}
}
我认为可以解决这个问题,但显然不会。
我还需要做什么?
我认为您还需要两件事:
就像vivek所说的那样,在您的Configure
方法中添加.UseCors()
到您的请求管道中。
添加.AllowAnyHeader()
到策略构建器中的CORS-Config中,我认为Content-Type
默认情况下-Header是不允许的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句