[软件设计/软件工程] 如何在 ASP.NET Core 中启用 CORS

[复制链接]
发表于 2022-5-6 16:00:36
问题
我试图在我的 ASP.NET Core Web API 上启用跨域资源共享,但我卡住了。

EnableCors 属性接受类型为 policyName 的字符串作为参数:
  1. // Summary:
  2. //     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
  3. //
  4. // Parameters:
  5. //   policyName:
  6. //     The name of the policy to be applied.
  7. public EnableCorsAttribute(string policyName);
复制代码

政策名称是什么意思?如何在 ASP.NET Core Web API 上配置 CORS?

回答
CORS 策略必须在应用程序启动时在 ConfigureServices 方法中配置:
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
  4.     {
  5.         builder.AllowAnyOrigin()
  6.                .AllowAnyMethod()
  7.                .AllowAnyHeader();
  8.     }));

  9.     // ...
  10. }
复制代码

CorsPolicyBuilder 中的构建器允许您根据需要配置策略。该策略现在可以使用此名称应用于控制器和操作:

[EnableCors("MyPolicy")]

或将其应用于每个请求:
  1. public void Configure(IApplicationBuilder app)
  2. {
  3.     app.UseCors("MyPolicy");

  4.     // ...

  5.     // This should always be called last to ensure that
  6.     // middleware is registered in the correct order.
  7.     app.UseMvc();
  8. }
复制代码






上一篇:使用resolve eject将promise转换为异步函数
下一篇:AngularJS 只显示某些类别

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表