【发布时间】:2021-09-19 14:29:54
【问题描述】:
我创建了以下...
- 一个在 IIS 上运行的后端 .NET Core POST API
- 使用 Angular CLI 创建并分别使用端口 8888 和 9999 运行的两个 UI 应用
- 我已在 .NET Core 应用程序中启用 CORS
在 .NET Core 中集成 CORS 时,我在 startup.cs 中添加了以下内容
Startup.cs
public class Startup
{
readonly string _allowSpecificOrigins = "_allowOrigin";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(policy =>
{
policy.AddPolicy(name: _allowSpecificOrigins, options => options.WithOrigins("http://localhost:9999").AllowAnyHeader().AllowAnyMethod());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors(options => options.WithOrigins("http://localhost:9999").AllowAnyHeader().AllowAnyMethod());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(_allowSpecificOrigins);
});
}
}
CORS 按预期完美运行。为了测试,我创建了两个 Angular 应用程序,它们使用两个不同的端口 8888 和 9999 运行。端口 9999 已配置并允许在 startup.cs 中访问 API。因此,从 PORT 9999 应用程序可以访问 API,而具有 PORT 8888 端口的应用程序由于 CORS 错误而无法访问 API,正如您所看到的响应。
API response when calling from the url http://localhost:8888
API response when calling from the url http://localhost:9999
现在的问题是,在覆盖所有标题后,我仍然可以从 POSTMAN 访问相同的 API
- 接受
- 接受编码
- 连接
- 参考
- 甚至是用户代理
Please look at the response received from POSTMAN
非常感谢任何帮助。谢谢。
【问题讨论】:
-
看来你的
Startup.cs实现CORS是正确的。POSTMAN有一些内部功能可以打破这一点,因此建议在这种情况下不要考虑POSTMAN,您可以尝试从其他Web App或Application访问应该强制执行CORS。让我知道您是否也可以从其他应用程序访问,然后我们可以进一步调查。 -
@MdFaridUddinKiron:为了测试,我创建了两个 Angular 应用程序,它们使用不同的端口 8888 和 9999 运行。端口 9999 已配置并允许在 startup.cs 中访问 API。因此,应用程序可以从 PORT 9999 访问 API,而使用 PORT 8888 的应用程序由于 CORS 错误而无法访问 API。
标签: angular asp.net-core cors postman