简体   繁体   English

ASP.NET Core 3.1 CORS 配置出错

[英]ASP.NET Core 3.1 CORS configuration gone wrong

The application is configured to use HTTPS.应用程序配置为使用 HTTPS。 We want to be able to make calls from the client to a printer on their local network that exposes a simple api that uses HTTP.我们希望能够从客户端调用本地网络上的打印机,该打印机公开使用 HTTP 的简单 api。 So from our javascript code we do a POST with a "text/plain" payload to send commands to the printer.因此,从我们的 javascript 代码中,我们使用“text/plain”有效负载执行 POST 以向打印机发送命令。 When we send this request we get the following error.当我们发送此请求时,我们收到以下错误。

jquery-3.3.1.min.js:2 Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://.../pstprnt'. jquery-3.3.1.min.js:2 混合内容:“https://...”页面已通过 HTTPS 加载,但请求不安全的 XMLHttpRequest 端点“http://.../pstprnt”。 This request has been blocked;此请求已被阻止; the content must be served over HTTPS.内容必须通过 HTTPS 提供。

Is there a way to configure CORS in such a way that only this traffic from and to a printer can be done using HTTP while the rest of the application uses HTTPS, without specifying the target IN startup.cs ?有没有办法以这样的方式配置 CORS,即只有这种进出打印机的流量可以使用 HTTP 完成,而应用程序的其余部分使用 HTTPS,而不指定目标 IN startup.cs ? ( this is because the printers should be able to be expanded at runtime, so basically just 'allow all orgins', so that its not restricted to the ones specified in Startup.cs) (这是因为打印机应该能够在运行时扩展,所以基本上只是“允许所有来源”,这样它就不会限制在 Startup.cs 中指定的那些)

I have tried multiple guides online, but I'm guessing there is something wrong with our Startup.cs file structure.我在网上尝试了多个指南,但我猜我们的 Startup.cs 文件结构有问题。

The request to the printer looks like this:对打印机的请求如下所示:

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

Here is a snippet our Startup file.这是我们的启动文件的片段。

CONFIGURE SERVICES配置服务

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


CONFIGURE配置

   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?}");
            });

 }


This doesn't relate to your ASP.NET CORS configuration, because you're making a request directly from the client (the browser) to the printer;这与您的 ASP.NET CORS 配置无关,因为您直接从客户端(浏览器)向打印机发出请求; CORS would come into play if you were making cross-domain requests to the ASP.NET API.如果您向 ASP.NET API 发出跨域请求,CORS 就会发挥作用。

What you could do is make the request to the printer from the server, instead, assuming your network topology permits it.您可以做的是从服务器向打印机发出请求,假设您的网络拓扑允许它。 Make an AJAX request from your JS to a new endpoint on the server, which then makes a plain HTTP request to the printer.从您的 JS 向服务器上的新端点发出 AJAX 请求,然后向打印机发出纯 HTTP 请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM