CORS:对预检请求的响应未通过访问控制检查

时间:2019-04-18 18:56:24

标签: ajax cors xmlhttprequest cross-domain

它显示的CORS问题:

选项https://dev-01-api-apptracker2/Admin 401(未经授权)

从原点“ https://dev-01-api-apptracker2/Admin”到“ https://dev-01-web-apptracker2”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。

但是我想我已经在ajax代码中添加了标头'Access-Control-Allow-Origin':'*',并尝试了多种方法来解决这些CORS问题,我设置了dataType:'json',crossDomain:true ,并且withCredentials:true,并且还添加了其他原始域。但是我仍然会出错。 我不知道这有什么问题,有人可以帮助我。谢谢!

AddAdmin: function (callback, UserId) {
        $.ajax({
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Access-Control-Allow-Headers': 'origin, X-Custom-Header',
                'Access-Control-Allow-Method': 'POST',
                'Access-Control-Allow-Origin': '*'
            },
            contentType: 'application/json',
            method: "POST",
            url: Services.APIBaseUrl + "Admin",
            dataType: 'json',
            crossDomain: true,
            data: JSON.stringify(UserId),
            xhrFields: {
                withCredentials: true
            },
            complete: function (data) {
                callback(data);
            }
        });
    },
public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("APIAllowedOriginsPolicy",
                builder =>
                {
                    builder.WithOrigins("https://dev-01-web-apptracker2",
                        "http://localhost:31474")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });
            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("APIAllowedOriginsPolicy"));
            });
            services.AddAuthentication(IISDefaults.AuthenticationScheme);

            // Add framework services.
            services
                .AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                });
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            //app.UseCors("APIAllowedOriginsPolicy");

            app.UseCors(builder =>
                builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
            );

            app.UseMvc();
        }

1 个答案:

答案 0 :(得分:0)

我发现了由于IIS身份验证问题而引起的问题,它需要允许Windows身份验证和匿名访问CORS。