.net core 3.1 c# cors 不适用于 angular 7

苏维希·瓦尔桑

嗨,我尝试了不同的方法来启用 cors,但我的代码失败了。我使用 spa 应用程序来呈现数据,但无法通过 cors.browser 显示错误跨源请求被阻止:同源策略不允许在http读取远程资源://localhost:5000/Values(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

 public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllers().AddNewtonsoftJson(opt =>
        {
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
        services.AddCors();
        services.AddSignalR();
        services.AddControllersWithViews();
        services.AddDbContext<DataContext>(x =>
        {
            x.UseLazyLoadingProxies();
            x.UseMySql(Configuration.GetConnectionString("DefaultConnection"));
        });
        IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
        {opt.User.RequireUniqueEmail = true;            
        }).AddRoles<IdentityRole>();
        builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
        builder.AddEntityFrameworkStores<DataContext>();
        builder.AddSignInManager<SignInManager<User>>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                        .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false

                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken) == false)
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });
        services.AddAuthorization(options =>
        {
            options.AddPolicy(constant.RequireVisionTrackAdminRole, policy => policy.RequireRole(constant.VisionTrackAdmin));
            options.AddPolicy(constant.RequireAdminRole, policy => policy.RequireRole(constant.Admin, constant.VisionTrackAdmin));
        });
        services.AddScoped<IAuthRepository, AuthRepository>();
        services.AddAutoMapper(typeof(VisionTrackRepository).Assembly);
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });
    }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }       
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();          
        app.UseRouting();
        app.UseCors(
            options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
        );
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<VisionTrackHub>("/VisionTrack").RequireCors("CorsPolicy");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}").RequireCors("CorsPolicy");

        });
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });

    }

也试过这个指南不起作用 [ https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1]是因为授权中间件还是要在端点上做些什么?

哈桑·蒙杰兹

在您的Startup文件中,您有两个主要方法ConfigureServices、 和Configure方法。

在你的ConfigureServices方法中定义如下:

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
        });

并在Configure方法中添加这一行:

app.UseCors("CorsPolicy");

注意: app.UseCors("CorsPolicy")应该在app.UseRouting()之前和之后app.UserAuthentication()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

linq2db 3.0.0-preview.1 不适用于 .net core 3

ASP.NET Core CORS配置不适用于Firefox

Visual Studio 2017 Docker支持不适用于ASP.Net Core Angular或React项目

忘记密码不适用于.NET Core 3.x和React支架

编辑并继续不适用于VS 2019(C#)的asp.net core 3.0

Nunit 测试不适用于 .Net Core C# 显示以下异常

依赖项注入不适用于IConfiguration C#.Net Core

Django + Angular CORS 不适用于 POST

Asp.net Core和Angular 7 Cors

Asp.Net Core 3.1 post 请求不适用于服务器上的 Angular 8

C#asp.net核心HTTP POST请求适用于邮递员,但不适用于我的Angular客户端(404错误)

FromBody路由不适用于ASP.NET Core

.net Core API 不适用于 IIS

.Net Core外部登录不适用于Chrome

Angular 7-Autoprefixer不适用于CSS Grid

bootsrap轮播不适用于angular 7

摩纳哥deltaDecorations不适用于angular 7

Angular 7 HttpClient:ToPromise不适用于放置请求

.NET CORE 3.1仅适用于Linux,不适用于Windows?

Angular 2 不适用于 Bootstrap 3 或 4

CSS3 动画不适用于 angular 4

对外部 API 的 HTTP 请求适用于 .NET,但不适用于 React(CORS 问题)

CORS Cookie可用于获取请求,但不适用于Angular2中的发布

适用于.NET Core的C#SharpZipLib

启用了Lambda函数Cors的AWS API Gateway不适用于Angular 5

使用SIGNAL R的Angular 7和ASP.NET Core 2.2的CORS策略问题

CI 3的方法不适用于php 5.6版本,但适用于php 7

angular js,asp.net mvc:$ http仅适用于ApiController而不适用于普通Controller吗?

.NET CORE 2.0 Angular 5:允许Cors