【发布时间】:2022-01-25 09:48:10
【问题描述】:
我想将 .NET Web API 上传到域,然后设置前端以连接到它。问题是由于同源策略,我无法向 API 域发送请求。我尝试使用 CORS 并允许所有来源,但由于凭据是通过响应发送的,我必须指定可以连接到 API 的确切域。
这是我在后端项目中使用的代码:
app.UseCors(x => x
.WithOrigins("https://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
当我尝试登录时,我在控制台中收到此错误:
Access to fetch at 'https://api.paykanpars.com/api/user/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
当我在 localhost 上运行 API 时,这可以正常工作,但是当我在生产主机上运行它时,它会返回 404 状态以响应预检请求。生产主机使用 Plesk 作为其网络主机。
【问题讨论】:
-
你能在你的 ConfigureServices 中试试这个吗: services.AddCors(options => options.AddDefaultPolicy(policy => policy.AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .SetIsOriginAllowed(_ => true )));这在您的配置中:app.UseCors();如果它有效,您可以修改它以阻止来自 3000 以外的请求
-
那也不行。
标签: http asp.net-web-api cors plesk