[Yugong Series] July 2023 .NET CORE tool case - GraphQL.Server (Cors cross-domain configuration)


foreword

CORS (Cross-Origin Resource Sharing) is a mechanism that allows web applications running in a browser to access resources from different origins. A different origin means that the URI (usually protocol, domain name, and port) is different from the document executing the current code. CORS provides a secure way for web developers to use cross-origin resources in web browsers while protecting users' privacy and data security. It does this by adding specific response headers to the HTTP headers, allowing the server to specify which domain names or IP addresses can access its resources.

1. Cors cross-domain configuration

1. Installation package

To setup CORS in .NET Core to allow cross-origin access to GraphQL server, you can follow the steps below:

  1. Install the Microsoft.AspNetCore.Cors package in a .NET Core web application.

    Install-Package Microsoft.AspNetCore.Cors
    
  2. In Startup.csthe file, add the CORS service to the application's services collection.

    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();
            });
        }
    }
    

    In the above code, we ConfigureServicesadded a CORS policy in the method and named it CorsPolicy. In Configurethe method, we add the CORS middleware to the application's request pipeline.

    It is worth noting that AllowAnyOrigin()cross-domain requests from any origin will be allowed, which is not safe. It is better to specify the domains that are allowed to be accessed, for example:

    options.AddPolicy("CorsPolicy",
        builder => builder.WithOrigins("http://example.com")
        .AllowAnyMethod()
        .AllowAnyHeader());
    
  3. Enable CORS on the GraphQL controller.

    Assuming your GraphQL controller is named GraphQLController, you need to apply an attribute on that controller class [EnableCors]to enable CORS.

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Cors;
    
    [EnableCors("CorsPolicy")]
    [Route("[controller]")]
    [ApiController]
    public class GraphQLController : ControllerBase
    {
          
          
        // 在此添加GraphQL相关的操作
    }
    

    In the code above, we EnableCorsapply the attribute to GraphQLControllerthe controller class and specify CorsPolicythe CORS policy named .

2. use

The usage code in GraphQL.Server is as follows:

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();

Guess you like

Origin blog.csdn.net/aa2528877987/article/details/131980448