在ASP.NET核心MVC项目上启用CORS

问题描述

当我最终了解我的问题是CORS阻止了我时,我需要将用户重定向到另一个页面,我试图弄清楚如何将CORS启用到我要重定向到的特定URL上而没有任何运气...也许有人可以发现我的错误

  public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UsebrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/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();
        _scheduler.JobFactory = new AspnetCoreJobFactory(app.applicationservices);
        app.UseSession();
        app.UseStaticFiles();
        app.UseCors(MyAllowSpecificOrigins);
        app.UseAuthentication();
        app.UseRouting();
        app.UseAuthorization();
        app.UseCookiePolicy();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",pattern: "{controller=Users}/{action=Dashboard}/{id?}");
        });
    }

public void ConfigureServices(IServiceCollection services)
    {
        FACEBOOK_APP_ID = _config.GetValue<string>("FACEBOOK_APP_ID");
        FACEBOOK_APP_SECRET = _config.GetValue<string>("FACEBOOK_APP_SECRET");
        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            options.HttpsPort = 44300;
        });
        services.AddHttpClient();
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,builder =>
                              {
                                  builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
                              });
        });
        services.AddMvc();
        services.AddIdentity<ApplicationUser,IdentityRole>(options => options.User.AllowedUserNameCharacters = null).AddEntityFrameworkStores<AppDbContext>();
        services.AddControllersWithViews();
        services.AddDbContextPool<AppDbContext>(options => options.UsesqlServer(_config.GetConnectionString("AutoloverDbConnection"),x => x.MigrationsAssembly("AutoMatcherProjectAss")).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
        services.AddTransient<AppDbContext>();
        services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
        services.AddSingleton<IActionContextAccessor,ActionContextAccessor>();
        services.AddSingleton<ISessionManager,ClientSIdeSessionManager>();
        services.AddHttpContextAccessor();
        services.AddSession();
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AdddistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(60);//You can set Time   
            options.Cookie.HttpOnly = true;
        });
        services.AddTransient<ISche,SchedulerImpl>();
        services.AddTransient<IQueue,QueueImpl>();
        services.AddTransient<SchedulerJob>();
        services.AddTransient<IBotFactory,BotFactory>();
        services.AddTransient<IJsonFactory,JsonFactory>();
        services.AddTransient<ICredentialDb,CredentialDb>();
        services.AddSingleton(provider => _scheduler);
        services.AddAuthentication().AddFacebook(options =>
        {
            options.AppId = FACEBOOK_APP_ID;
            options.AppSecret = FACEBOOK_APP_SECRET;
            options.Savetokens = true;

        });

        _scheduler.Clear();
    }

控制器:

    [HttpPost]
    public async Task<IActionResult> AuthenticateInstagramAPI(Service service)
    {

        return new RedirectResult("https://www.instagram.com/");

    }

错误

从来源“ https:// localhost:44300”访问“ https://www.instagram.com/”(从“ https:// localhost:44300 / Actions / AuthenticateInstagramAPI”重定向)的XMLHttpRequest的访问已被阻止根据CORS政策:在飞行前响应中,Access-Control-Allow-Headers不允许使用请求标头字段x-requested-with。

编辑----------

客户端AJAX调用

function AuthInstagram() {
    var service = $('#userServicesDropDownAuth :selected').text()
    $.ajax({
        url: '/Actions/AuthenticateInstagramAPI',method: 'POST',data: service,dataType: 'json',success: function (data) {
            console.log(data);
        },error: function (error) {
            //alert(error+"11");
        }
    })   

}

解决方法

在startup.cs中。您将 app.UseCors(MyAllowSpecificOrigins);放在app.UseStaticFiles();app.UseAuthentication();之间

doc中,Calls the UseCors extension method and specifies the _myAllowSpecificOrigins CORS policy. UseCors adds the CORS middleware. The call to UseCors must be placed after UseRouting,but before UseAuthorization. For more information,see Middleware order.

因此您可以像这样更改数据:

    app.UseRouting();

    app.UseCors(MyAllowSpecificOrigins);


    app.UseAuthorization();
,

想通了。

会显示出是否向Controller动作发送了AJAX get请求,并尝试从该动作进行重定向,但该动作无效。 可能是AJAX添加了一些标头,还是AJAX调用没有通过中间件管道进行?不知道,如果有人知道我为什么要这样做的答案!