簡體   English   中英

在 ASP.NET 核心 MVC 項目上啟用 CORS

[英]Enable CORS on an ASP.NET core MVC project

當我終於明白我的問題是 CORS 阻止了我時,我需要將用戶重定向到另一個頁面發現我的錯誤?

  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();
    }

controller:

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

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

    }

錯誤:

CORS 策略已阻止從源“https://localhost:44300”訪問“https://www.instagram.com/”處的 XMLHttpRequest(從“https://localhost:44300/Actions/AuthenticateInstagramAPI”重定向) :請求 header 字段 x-requested-with 在預檢響應中被 Access-Control-Allow-Headers 不允許。

編輯 - - - - -

客戶端 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. 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 獲取請求,並嘗試從該操作重定向它不會起作用。 可能是 AJAX 添加了一些標頭,或者 AJAX 調用不是 go 通過中間件管道? 不知道,如果有人知道我為什么會appriciate的答案!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM