通过 Ngrok 远程访问 ASP.NET Core 6 Web API 时出现 CORS 错误

问题描述 投票:0回答:1

我使用 ASP.NET Core 6 开发了一个 Web API,我想在部署之前对其进行远程测试。为了实现这一目标,我使用 Ngrok 将我的本地服务器公开给公共 URL。

Ngrok 生成的 URL 工作正常并且每个人都可以访问。但是,当我尝试使用此 URL 从 API 获取数据时,遇到 CORS(跨源资源共享)错误。

需要注意的是,我已经在 Program.cs 文件中配置了 CORS,并且当我从同一设备上的 API 获取数据时没有任何问题。

enter image description here

enter image description here

我做了什么:

- I've configured CORS in the Program.cs file using AddCors and UseCors methods.
- I'm able to access the API endpoints locally without any CORS issues.
- I've generated a Ngrok URL that points to my local server and verified that it's working.
- I've ensured that my API controllers have the \[ApiController\] attribute.
- I've added the appropriate CORS policies to allow all origins during testing.
asp.net-web-api cors ngrok
1个回答
0
投票

据我所知,您的配置几乎是正确的,但请确保中间件配置的顺序正确。例如,确保将 CORS 中间件放置在任何身份验证中间件(如

app.UseAuthentication()
)之前。

© www.soinside.com 2019 - 2024. All rights reserved.