Blazor和Webapi Cors支持

时间:2020-07-23 15:32:27

标签: cors asp.net-core-webapi blazor-webassembly

我花了几天的时间试图解决这个问题。我发现的所有示例都不起作用,或者我不了解。我目前在https:// localhost:5001上运行一个.netCore webapi,在https:// localhost:5002上运行一个独立的blazor Webassembly。从blazor我发起一个http请求:

protected async override void OnInitialized()
{
    base.OnInitialized();
    string reqUrl = $"https://localhost:5001/api/District/";
    var response = await http.GetAsync(reqUrl);
}

在webapi上,我有以下startup.cs:

public class Startup
{
        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();
        // For Entity Framework  
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));

        // For Identity  
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Adding Authentication  
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })

        // Adding Jwt Bearer  
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = Configuration["JWT:ValidAudience"],
                    ValidIssuer = Configuration["JWT:ValidIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
                };

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                    builder =>
                                    {
                                        builder.WithOrigins("https://localhost:5002/");
                                    });
            });

        });
    }


// 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.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();
        app.UseCors("CorsPolicy");

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

我在执行时遇到此错误:

访问CORS策略已阻止从源“ https:// localhost:5002”获取“ https:// localhost:5001 / api / District /”的访问:没有“ Access-Control-Allow-Origin”标头存在于请求的资源上。如果不透明的响应可以满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。

任何人都可以建议进行更改以使其正常工作吗?我去过MS Docs,但这就像尝试用阿拉伯语古兰经...

2 个答案:

答案 0 :(得分:0)

UseCors的呼叫必须放在UseRouting之后,但要放在UseAuthorization之前:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseCors("CorsPolicy");

    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

参考:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware

答案 1 :(得分:0)

此代码对我有用:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors(options => options.AddPolicy(
              "_mypolicy", builder => builder
              .AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader()
          )
           );
    }

    // 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.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("_mypolicy");

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }