ASP.NET Core 中的跨域资源共享 (CORS) 配置
ASP.NET Core 中的跨域资源共享 (CORS) 是一项安全功能,允许您的 Web 应用程序向来自不同来源(例如不同的域、协议或端口)的资源发出请求。要启用 CORS,您需要配置一个 CORS 策略。
创建 CORS 策略
ASP.NET Core 中的 EnableCors
属性接受一个 policyName
参数,该参数指定要应用的 CORS 策略的名称。策略名称只是一个字符串标识符,您可以稍后使用它来引用该策略。
要创建 CORS 策略,您可以在 Startup
类的 ConfigureServices
方法中使用 IServiceCollection.AddCors
方法:
<code class="language-csharp">public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("MyCorsPolicy", builder => { builder.WithOrigins("http://example.com", "https://www.contoso.com") .AllowAnyMethod() .AllowAnyHeader(); }); }); }</code>
在此示例中,创建了一个名为“MyCorsPolicy”的 CORS 策略。此策略允许来自两个特定来源(“https://www.php.cn/link/8be904ad045c578053fc6052578f9324 HTTP 方法和标头。
应用 CORS 策略
创建 CORS 策略后,您可以将其应用于特定的控制器、操作或整个应用程序。要将其应用于单个控制器,请使用 [EnableCors]
属性:
<code class="language-csharp">[EnableCors("MyCorsPolicy")] public class MyController : Controller { // ... }</code>
要将策略应用于每个请求,请在 Configure
方法中将 UseCors
中间件添加到应用程序管道:
<code class="language-csharp">public void Configure(IApplicationBuilder app) { app.UseCors("MyCorsPolicy"); // ... }</code>
这将确保对应用程序的所有请求都受“MyCorsPolicy”策略的约束。
以上是如何在 ASP.NET Core 中配置跨域资源共享 (CORS)?的详细内容。更多信息请关注PHP中文网其他相关文章!