【问题标题】:How to handle double requests from the client in ASP.NET Core 5.0?如何在 ASP.NET Core 5.0 中处理来自客户端的双重请求?
【发布时间】:2021-12-13 09:13:22
【问题描述】:

客户端应用程序对服务器上的单个资源进行双重查询。第一帧没有授权头,第二帧有。不幸的是,在读取第一帧之后,服务器没有得到第二帧。在 ASP.NET CORE 5 服务器上如何处理?

测试端点。 当我从客户端调用时,值总是 = {},从邮递员那里一切正常

        [ApiExplorerSettings(IgnoreApi = true)]
        [HttpPost("Service")]
        public IActionResult GetHeader()
        {
            var value = HttpContext.Request.Headers["Authorization"];
            return Ok();
        }
        app.UseMiddleware<SerilogMiddleware>();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotificationHub>("/api/socket");
            endpoints.UseSoapEndpoint<SVPService.SVPServiceSoap>((options) =>
            {
                options.Path = "/Service.asmx";
                options.Binding = new BasicHttpBinding()
                {
                    TextEncoding = new UTF8Encoding(false),
                    Security = new BasicHttpSecurity()
                    {
                        Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                        Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.Basic }
                    }
                };
                options.SoapSerializer = SoapSerializer.XmlSerializer;
            }).RequireAuthorization();
        });
        app.UseMvc();

来自 node.js 服务器上客户端的记录请求以获取标头。

First Request Headers
{
  'user-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)',
  'content-type': 'text/xml; charset=utf-8',
  'content-length': '806',
  expect: '100-continue',
  connection: 'Keep-Alive'
}
Second Request Headers
{
  'user-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.42000)',
  'content-type': 'text/xml; charset=utf-8',
  authorization: 'Basic dGVzdG93ZV91c2VybmFtZTp0ZXN0b3dlX3Bhc3N3b3Jk',
  'content-length': '806',
  expect: '100-continue'
}

这是我的 startup.cs 文件

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    //.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials().SetIsOriginAllowed(hostName => true);
                
            }));
            
            services.AddQuartz();

            services.Configure<JwtAuthentication>(Configuration.GetSection("JwtAuthentication"));
            services.AddAuthentication("BasicAuthentication")
                .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "xxx",
                    Title = "xxx",
                    Description = "xxx",
                    Contact = new OpenApiContact
                    {
                        Name = "xxx",
                        Email = "xxx",
                        Url = new Uri("xxx"),
                    },
                });

                // Set the comments path for the Swagger JSON and UI.
                string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            MapperConfiguration mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);

            services.AddSignalR().AddNewtonsoftJsonProtocol();
            services.AddSingleton<ITokenService, TokenService>();
            services.AddSingleton<IPasswordService, PasswordService>();
            services.AddSingleton<IUserProfile, UserProfile>();
            services.AddSingleton<IReceiptService, ReceiptService>();
            services.AddSingleton<ISend, Send>();
            services.AddSingleton<IEncryption, Encryption>();
            services.AddSingleton<ParkingTicketManagementServiceV3, TicketManagement>();
            services.AddScoped<SVPService.SVPServiceSoap, SVPServiceSoap>();
            services.AddScoped<IManageSVP, ManageSVP>();
            services.AddScoped<IStripeMethods, StripeMethods>();
            services.AddScoped<IManageSchedullerRecurringPayment, ManageSchedullerRecurringPayment>();
            services.AddRepository();
            services.AddSingleton<IAuthorizationHandler, DenyAnonymousAuthorizationRequirement>();

            services.AddMvc(options =>
            {
                options.InputFormatters.Insert(0, new RawJsonBodyInputFormatter());
                options.EnableEndpointRouting = false;

            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new LowerCaseNamingStrategy() };
                opt.SerializerSettings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.Default;
                opt.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                opt.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                opt.SerializerSettings.MaxDepth = null;
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddSwaggerGenNewtonsoftSupport();

            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "StaticFile")),
                RequestPath = "/staticfile"
            });

            app.UseCors("CorsPolicy");
            app.UseHttpsRedirection();
            app.UseSwagger();

            app.UseReDoc(c =>
            {
                c.SpecUrl = "xxx";
                c.DocumentTitle = "xxx";
            });

            app.UseMiddleware<SerilogMiddleware>();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<NotificationHub>("/api/socket");
                endpoints.UseSoapEndpoint<SVPService.SVPServiceSoap>((options) =>
                {
                    options.Path = "/Service.asmx";
                    options.Binding = new BasicHttpBinding()
                    {
                        TextEncoding = new UTF8Encoding(false),
                        Security = new BasicHttpSecurity()
                        {
                            Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                            Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.Basic }
                        }
                    };
                    options.SoapSerializer = SoapSerializer.XmlSerializer;
                }).RequireAuthorization();
            });
            app.UseMvc();
        }
    }

【问题讨论】:

  • 也许我错了,但我认为我们需要查看一些代码来弄清楚为什么会发出两个请求。也许一些前端客户端代码、端点代码或类似的?如果您知道什么代码单元会导致它
  • @thesystem 我没有在客户端应用程序中预览代码源。所以我不能发送这样的东西。我假设情况与本文“stackoverflow.com/questions/6338942/…”中描述的情况相似,但是客户端应用程序中没有更改代码我正在寻找可以在服务器端使用的解决方案。
  • 啊好吧,现在我明白了。我以为您也可以访问前端/客户端代码。我不确定我是否可以立即提供帮助(从未遇到过这种情况),但现在问题/问题更加清楚了。还是很有趣的问题,希望有人过来帮忙
  • 您能否edit 将代码作为文本而不是图像包含在内? StackOverflow 使用 markdown 获得漂亮的代码区 :)
  • @thesystem 我粘贴了端点代码

标签: c# asp.net .net-core


【解决方案1】:

只需检查响应是否包含正确的标头

【讨论】:

    【解决方案2】:

    是的, 为了回答我的问题,标题实际上缺少 WWW-Authenticate: Basic realm = 标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多