CORS(Cross-Origin Resource Sharing)是一种机制,允许在浏览器中运行的Web应用程序访问不同源的资源。不同源是指URI(通常是协议,域名和端口)与执行当前代码的文档不同。CORS为Web开发人员提供了一种安全的方式来在Web浏览器中使用跨域资源,同时保护用户的隐私和数据安全。它通过在HTTP头中添加特定的响应头来实现,允许服务器指定哪些域名或IP地址可以访问其资源。
在.NET Core中设置CORS以允许跨域访问GraphQL服务器,您可以遵循以下步骤:
在.NET Core Web应用程序中安装Microsoft.AspNetCore.Cors软件包。
Install-Package Microsoft.AspNetCore.Cors
在Startup.cs
文件中,将CORS服务添加到应用程序的服务集合中。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Cors;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
// 在此添加其他服务
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy"); // 添加CORS中间件
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
在上面的代码中,我们在ConfigureServices
方法中添加了一个CORS策略,并将其命名为CorsPolicy
。在Configure
方法中,我们将CORS中间件添加到应用程序的请求管道中。
值得注意的是,AllowAnyOrigin()
会允许任何来源的跨域请求,这是不安全的,更好的做法是指定允许访问的域,例如:
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://example.com")
.AllowAnyMethod()
.AllowAnyHeader());
在GraphQL控制器上启用CORS。
假设您的GraphQL控制器名称为GraphQLController
,则需要在该控制器类上应用[EnableCors]
特性,以启用CORS。
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
[EnableCors("CorsPolicy")]
[Route("[controller]")]
[ApiController]
public class GraphQLController : ControllerBase
{
// 在此添加GraphQL相关的操作
}
在上面的代码中,我们将EnableCors
特性应用到GraphQLController
控制器类上,并指定名称为CorsPolicy
的CORS策略。
在GraphQL.Server中的使用代码如下:
using GraphQL;
using Chat = GraphQL.Samples.Schemas.Chat;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<Chat.IChat, Chat.Chat>();
builder.Services.AddGraphQL(b => b
.AddAutoSchema<Chat.Query>(s => s
.WithMutation<Chat.Mutation>()
.WithSubscription<Chat.Subscription>())
.AddSystemTextJson());
builder.Services.AddRouting();
builder.Services.AddCors(options =>
{
options.AddPolicy("MyCorsPolicy", b =>
{
b.AllowCredentials();
b.WithOrigins("https://localhost:5001");
});
});
var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseWebSockets();
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints =>
{
// configure the graphql endpoint at "/graphql"
endpoints.MapGraphQL("/graphql")
.RequireCors("MyCorsPolicy");
// configure Playground at "/"
endpoints.MapGraphQLPlayground("/");
});
await app.RunAsync();
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有