【发布时间】:2020-10-12 09:57:51
【问题描述】:
我以为我允许访问所有来源,但我仍然收到此错误。
在 'localhost:60248/api/page/1' 从源访问 XMLHttpRequest “http://localhost:4200”已被 CORS 策略阻止:跨源 请求仅支持协议方案:http、data、chrome、 chrome 扩展,https。
UPDATE在添加建议的代码更改后,该错误现已更改。现在是这样的:
从 'http://localhost:60248/api/page/1' 访问 XMLHttpRequest 来源 'http://localhost:4200' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查: 预检请求不允许重定向。
在 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);
}
}
我以为这样可以解决问题,但显然不是。
我还需要做什么?
【问题讨论】:
-
向我们展示您使用的 Javascript 代码 - 您是否使用了正确的 URL? URL 是否有
http或https前缀? -
添加了调用端点的 Angular 服务。
-
您确定网址中没有奇怪的字符吗?错误消息指出您没有使用
http。您是否设置了基本 URL? -
有趣,我会调查一下...
-
请停止更改您的问题 - 它已被回答,您现在正在提出一个新问题。将其标记为已回答,因为花时间帮助您的人不是无限资源,应因提供帮助而获得奖励。
标签: c# asp.net-core-webapi asp.net-core-3.1