【问题标题】:ASP.NET Core 3.1 CORS configuration gone wrongASP.NET Core 3.1 CORS 配置出错
【发布时间】:2021-01-03 11:12:25
【问题描述】:

应用程序配置为使用 HTTPS。我们希望能够从客户端调用本地网络上的打印机,该打印机公开了一个使用 HTTP 的简单 api。因此,从我们的 javascript 代码中,我们使用“text/plain”有效负载执行 POST 以向打印机发送命令。当我们发送此请求时,我们会收到以下错误。

jquery-3.3.1.min.js:2 混合内容:“https://...”处的页面是通过 HTTPS 加载的,但请求了不安全的 XMLHttpRequest 端点“http://.../pstprnt” '。此请求已被阻止;内容必须通过 HTTPS 提供。

有没有一种方法可以配置 CORS,使得只有进出打印机的流量可以使用 HTTP 完成,而应用程序的其余部分使用 HTTPS,而不指定目标 IN startup.cs? (这是因为打印机应该能够在运行时扩展,所以基本上只是'允许所有来源',因此它不限于 Startup.cs 中指定的那些)

我在网上尝试了多个指南,但我猜我们的 Startup.cs 文件结构有问题。

对打印机的请求如下所示:

$.ajax({
    type: "POST",
    url: "http://<printer-ip>/pstprnt",
    data: 'some ZPL',
    contentType: 'text/plain'
}).done((res) => {
    console.log("second success");
}).fail((e) => {
    alert(e);
})

这是一个 sn-p 我们的启动文件。

配置服务

        public void ConfigureServices(IServiceCollection services)
        {
            // Add Cors
            services.AddCors();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            /* (Verification/password reset) email sender */
            //services.AddTransient<IEmailSender, EmailSender>();
            //services.Configure<AuthMessageSenderOptions>(Configuration);

            Task.Run(() => {
                var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).Options;
                using (var dbContext = new ApplicationDbContext(options)) {
                    var model = dbContext.AankoopProduct;
                  
                }
            });



            services.AddLocalization();
            /*
               I commented this out because I am using UseEndpoints, Am I doing this correctly?

            services.AddMvc()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            */
          
            services.AddIdentity<Gebruiker, IdentityRole>(options =>
            {
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
                options.SignIn.RequireConfirmedEmail = true;
            }).AddEntityFrameworkStores<ApplicationDbContext>()
              .AddDefaultTokenProviders();

            services.Configure<IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = true;
                options.Password.RequiredLength = 6;
                options.Password.RequiredUniqueChars = 1;
            });

            services.AddControllersWithViews().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            // .cshtml views & .razor components 
            services.AddRazorPages();

            //SignalR for Websockets
            services.AddSignalR();

            // reload views after changing JS 
#if DEBUG
            var mvcBuilder = services.AddControllersWithViews();
            mvcBuilder.AddRazorRuntimeCompilation();
            #endif


            services.ConfigureApplicationCookie(opts => opts.LoginPath = "/Account/Login");

            /* Breadcrumbs */
            services.AddBreadcrumbs(GetType().Assembly, options =>
            {
                options.TagName = "nav";
                options.TagClasses = "";
                options.OlClasses = "breadcrumb breadcrumb--transparent m-0";
                options.LiClasses = "breadcrumb-item";
                options.ActiveLiClasses = "breadcrumb-item active";
                //options.SeparatorElement = "<li class=\"separator\">/</li>";
            });
            /* Repositories */
            services.RegisterRepositories();

            services.AddSession();
        }


配置

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IVerkoopProductXMLRepository rep)
        {
            //app.ApplicationServices.GetService<IInkomendeBestellingTrackerSingleton>();


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            #region Auth
            var supportedCultures = new[]
            {
                new CultureInfo("nl-BE")
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("nl-BE"),
                // Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                // UI strings that we have localized.
                SupportedUICultures = supportedCultures
            });

            var cultureInfo = new CultureInfo("nl-BE");
            cultureInfo.NumberFormat.CurrencySymbol = "€";
            cultureInfo.NumberFormat.NumberDecimalSeparator = ".";

            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("nl-BE");
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("nl-BE");


            // To configure external authentication, 
            // see: http://go.microsoft.com/fwlink/?LinkID=532715

            #endregion

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseStatusCodePages();
            app.UseRouting();
            app.UseSession();

            // Enable Cors
            app.UseCors();
            /*
              I commented this out because I am using UseEndpoints() , Am I doing this correctly?
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=UserSelection}/{id?}");
            });
            */
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Account}/{action=Login}/{id?}");
            });

 }


【问题讨论】:

  • 这跟javascript有什么关系?
  • 我将添加 Javascript sn-p :-)
  • 您为什么认为这与 CORS 有关?据我所知,这是一个与 CORS 无关的 browser security feature
  • @KevinChristopherHenry 我认为这是一个 CORS 问题,因为错误让我这样想,也许错误误导了我?
  • @AndrewMorton 今天我和他们通了半个小时的电话,但技术部门“害怕他们无能为力”

标签: javascript asp.net-mvc http asp.net-core mixed-content


【解决方案1】:

这与您的 ASP.NET CORS 配置无关,因为您是直接从客户端(浏览器)向打印机发出请求;如果您向 ASP.NET API 发出跨域请求,CORS 就会发挥作用。

您可以做的是从服务器向打印机发出请求,而不是假设您的网络拓扑允许它。从您的 JS 向服务器上的新端点发出 AJAX 请求,然后向打印机发出纯 HTTP 请求。

【讨论】:

  • 亲爱的 Dylan,我不能从服务器执行此操作,因为这需要我们的服务器知道我们拥有的每个客户端的 IP 地址(~200),而且连接到他们的域并使用该打印机。相反,我希望他们将标签打印机的 IP 地址添加到表中,以便他们可以使用 JavaScript 从客户端打印到该表
  • 不幸的是,必须连接到域是一个问题;你可能不走运。发现打印机 IP 不是问题,您可以让 JS 将 IP 作为请求的一部分发送到服务器。
猜你喜欢
  • 1970-01-01
  • 2020-11-24
  • 2022-01-18
  • 2021-12-20
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多