如何在apache2服务器中运行的.net core 2项目中启用cors

时间:2018-12-18 19:41:42

标签: cors asp.net-core-2.1

我正在使用dotnet core 2.1创建Web api项目。我在Linux服务器上部署了该项目。部署后,我可以登录到我的站点。但是在我的本地计算机上,它可以正常工作。

我使用邮递员发送登录请求,然后它将返回令牌。仅当我通过网站发送此请求时才会发生此错误。

这是我得到的错误 无法加载资源:net :: ERR_CONNECTION_REFUSED

nav.component.ts:31 true
1
2
3
error
[object XMLHttpRequest]
[object XMLHttpRequest]
2
15011.100000001534
[object XMLHttpRequest]
true

function composedPath() { [native code] }
function stopPropagation() { [native code] }
function stopImmediatePropagation() { [native code] }
function preventDefault() { [native code] }
function initEvent() { [native code] }
function stopImmediatePropagation() { [native code] }

我认为这个问题正在cors中发生 我也在中间件和Apache服务器中启用了cors

这是启动类中的代码

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.AddDbContext<DataContext>(s => s.UseMySql(Configuration.GetConnectionString("DefaultConnection"))
        .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));

        IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
        {
            opt.Password.RequireDigit = false;
            opt.Password.RequiredLength = 4;
            opt.Password.RequireNonAlphanumeric = false;
            opt.Password.RequireUppercase = false;

        });

        builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
        builder.AddEntityFrameworkStores<DataContext>();
        builder.AddRoleValidator<RoleValidator<Role>>();
        builder.AddRoleManager<RoleManager<Role>>();
        builder.AddSignInManager<SignInManager<User>>();



        // services.AddAuthorization(options => {
        //     options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
        //     options.AddPolicy("SuperAdminPhotoRole", policy => policy.RequireRole("SuperAdmin"));
        // });

        services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(opt =>
        {
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });
        services.AddCors();
        services.AddAutoMapper();
        services.AddTransient<Seed>();
        services.AddScoped<IAuthRepository, AuthRepository>();
        services.AddScoped<IDatingRepository, DatingRepository>();
        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
            };
        });
        services.AddScoped<LogUserActivity>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {

            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message);
                    }
                });
            });

            // app.UseHsts();
        }

        // app.UseHttpsRedirection();
        seeder.SeedUsers();
        app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
        app.UseAuthentication();
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseMvc(routes => {
            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "FallBack", action = "Index"}
            );
        });
    }
}

这是程序类

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseUrls("http://localhost:5000")
            .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>();
    }

这是打字稿代码

login(model: any) {
    return this.http.post(this.baseUrl + 'login', model).pipe(
      map((response: any) => {
        const user = response;
        if (user) {
          localStorage.setItem('token', user.token);
          localStorage.setItem('user', JSON.stringify(user.user));
          localStorage.setItem('role', user.roles[0]);
          this.currentUser = user.user;
          this.decodedToken = this.jwtHelper.decodeToken(user.token);
          this.userRole = user.roles[0];
         this.changeMemberPhoto(this.currentUser.photoUrl);
        }
      })
    );
  }

这是我遵循的在apache服务器中启用cors的方法 我编辑了apache2.conf文件并添加了此代码

<Directory /var/www/html>
     Options Indexes FollowSymLinks
     Order Allow,Deny
     Allow from all
     AllowOverride all
     Header set Access-Control-Allow-Origin "*"
     Require all granted
</Directory>

执行此命令后

a2enmod headers

请帮助我解决这个问题

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。这不是cors问题。问题出在Web项目环境变量api url在本地主机中。所以我将其更改为服务器ip地址,然后不再发生此错误。