如何在.NET Core 2项目中启用CORS在Apache2服务器中运行



我正在使用dotnet core 2.1.我在Linux Server中部署了此项目。正确。

我使用Postman并发送登录请求,然后如果我通过网站发送此请求,则只会返回token。

这是我遇到的错误无法加载资源: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中发生我在中间件中启用了CORS&Apache服务器也

这是启动类中的代码

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 Server中的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

请帮助我解决此问题

i解决了这个问题。这不是一个问题问题。再次。

最新更新