如何在 ASP.NET Core 5.0 中处理来自客户端的双重请求?

     2023-04-13     279

关键词:

【中文标题】如何在 ASP.NET Core 5.0 中处理来自客户端的双重请求?【英文标题】:How to handle double requests from the client in 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 我没有在客户端应用程序中预览代码源。所以我不能发送这样的东西。我假设情况与本文“***.com/questions/6338942/…”中描述的情况相似,但是客户端应用程序中没有更改代码我正在寻找可以在服务器端使用的解决方案。 啊好吧,现在我明白了。我以为您也可以访问前端/客户端代码。我不确定我是否可以立即提供帮助(从未遇到过这种情况),但现在问题/问题更加清楚了。还是很有趣的问题,希望有人过来帮忙 您能否edit 将代码作为文本而不是图像包含在内? *** 使用 markdown 获得漂亮的代码区 :) @thesystem 我粘贴了端点代码 【参考方案1】:

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

【讨论】:

【参考方案2】:

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

【讨论】:

如何确定在 C# ASP.NET CORE MVC 5.0 中选择了哪个单选按钮

】如何确定在C#ASP.NETCOREMVC5.0中选择了哪个单选按钮【英文标题】:HowtodeterminewhichradiobuttonwasselectedinC#ASP.NETCOREMVC5.0【发布时间】:2021-10-0805:02:50【问题描述】:我想检查从我的Index.cshtml文件中选择了哪个单选按钮,然后我想使用... 查看详情

ASP.Net Core 2 错误处理:如何在 Http Response 中返回格式化的异常详细信息?

】ASP.NetCore2错误处理:如何在HttpResponse中返回格式化的异常详细信息?【英文标题】:ASP.NetCore2errorhandling:HowtoreturnformattedexceptiondetailsinHttpResponse?【发布时间】:2018-07-1509:37:15【问题描述】:我正在寻找一种方法来返回调用我的W... 查看详情

在 Asp.Net Core 5.0 中注册 HttpClient 时注入 ILogger

】在Asp.NetCore5.0中注册HttpClient时注入ILogger【英文标题】:InjectILoggerwhenregisteringHttpClientinAsp.NetCore5.0【发布时间】:2021-12-1721:14:06【问题描述】:在Asp.NetCore中注册自定义服务时,例如:services.AddScoped<ISomeService,SomeService>();然... 查看详情

如何在 ASP.NET CORE 5.0 MVC 中将登录设置为默认路由

】如何在ASP.NETCORE5.0MVC中将登录设置为默认路由【英文标题】:HowtomakeLoginasDefaultrouteinASP.NETCORE5.0MVC【发布时间】:2021-03-2512:30:43【问题描述】:我试图在加载应用程序时在第一次启动时加载登录页面。到目前为止我尝试了什么... 查看详情

如何在 Asp.Net Core Mvc 5.0 中将 sql 数据库与 ado.net 连接?

】如何在Asp.NetCoreMvc5.0中将sql数据库与ado.net连接?【英文标题】:HowtoconnectsqlDatabasewithado.netinAsp.NetCoreMvc5.0?【发布时间】:2021-07-2716:40:20【问题描述】:我找不到我在哪里失踪。我的代码是这样的;users.cs:usingSystem;usingSystem.Coll... 查看详情

无法在 ASP.NET Core 5.0 下的 IIS 中托管 CoreWcf

】无法在ASP.NETCore5.0下的IIS中托管CoreWcf【英文标题】:CannothostCoreWcfinIISunderASP.NETCore5.0【发布时间】:2021-09-1606:02:15【问题描述】:我尝试将我的WCFWeb服务从.NetFramework4.7.1迁移到.Net5.0。我使用nuggetCoreWcf并尝试在IIS上运行它。阅... 查看详情

在 ASP.NET Core 中处理过期的刷新令牌

】在ASP.NETCore中处理过期的刷新令牌【英文标题】:HandlingExpiredRefreshTokensinASP.NETCore【发布时间】:2019-02-1000:27:28【问题描述】:解决此问题的代码见下文我正在尝试寻找最佳和最有效的方法来处理在ASP.NETCore2.1中已过期的刷新令... 查看详情

在 ASP.NET Core WebApi 中处理多个租户

】在ASP.NETCoreWebApi中处理多个租户【英文标题】:HandlingmultipletenantsinASP.NETCoreWebApi【发布时间】:2022-01-0816:41:21【问题描述】:我开发了.NETCoreWebApi应用程序,并且有几个不同的客户使用具有不同配置的同一个应用程序。(应用... 查看详情

如何在 ASP.NET Core 中强制执行小写路由?

】如何在ASP.NETCore中强制执行小写路由?【英文标题】:HowdoyouenforcelowercaseroutinginASP.NETCore?【发布时间】:2016-07-2109:40:38【问题描述】:在ASP.NET4中,这与应用程序的RegisterRoutes处理程序中的routes.LowercaseUrls=true;一样简单。我在ASP.... 查看详情

如何在 ASP.​NET Core 中使用 jquery

】如何在ASP.​NETCore中使用jquery【英文标题】:HowtousejqueryinASP.​NETCore【发布时间】:2016-10-2118:54:18【问题描述】:我创建了一个ASP.NET核心模板并编写了一个jquery脚本。当我查看页面时,我看到jquery已加载到页面中,但脚本没有... 查看详情

如何在 asp.net core 中编写自定义 actionResult

】如何在asp.netcore中编写自定义actionResult【英文标题】:HowtowritecustomactionResultinasp.netcore【发布时间】:2021-01-2621:15:45【问题描述】:在webApi2中,我可以通过继承IHttpActionResult来编写自定义ActionResult。示例:publicclassMenivaActionResult... 查看详情

如何使用 MVC 的内容协商在 ASP.NET Core MVC 中间件中返回响应?

】如何使用MVC的内容协商在ASP.NETCoreMVC中间件中返回响应?【英文标题】:HowcanIreturnaresponseinASP.NETCoreMVCmiddlewareusingMVC\'scontentnegotiation?【发布时间】:2018-01-1214:23:22【问题描述】:我有一些ASP.NETCoreMVC中间件来捕获我想从中返回... 查看详情

ASP.NET CORE 5.0 Identity 显示当前登录用户

】ASP.NETCORE5.0Identity显示当前登录用户【英文标题】:ASP.NETCORE5.0IdentityDisplaycurrentloggedinuser【发布时间】:2021-03-0309:26:36【问题描述】:我试图在IndexPage中显示哪个用户提交ticket。在我的模型中,我添加了属性publicint?UserIdget;set;pu... 查看详情

EF Core 5.0 - 更新 ASP.NET Core Web API 中的多对多实体

...【问题描述】:在EFCore5.0中引入了多对多关系。我被困在如何通过我的asp.netapi更新它们。对于一对一和一对多关系,有一个约定,只需添加属性名称和ID。publicclassB 查看详情

如何在 ASP.NET Core 中使用 npm

】如何在ASP.NETCore中使用npm【英文标题】:HowtousenpmwithASP.NETCore【发布时间】:2016-10-2211:26:20【问题描述】:我正在使用npm来管理我的ASP.NETCore应用程序所需的jQuery、Bootstrap、FontAwesome和类似的客户端库。对我有用的方法首先是在... 查看详情

即使在 asp.net core 5.0 中提供了不记名令牌,也会返回 401 [关闭]

】即使在asp.netcore5.0中提供了不记名令牌,也会返回401[关闭]【英文标题】:401isreturnedevenwhenbearertokenisproviedinasp.netcore5.0[closed]【发布时间】:2021-04-2109:01:11【问题描述】:所以我正在尝试为我的webapi应用程序设置身份验证。现在... 查看详情

在带有数据库的 ASP.NET Core 5.0 应用程序中使用 Serilog 实现日志记录

】在带有数据库的ASP.NETCore5.0应用程序中使用Serilog实现日志记录【英文标题】:ImplementLoggingUsingSerilogInASP.NETCore5.0ApplicationWithDatabase【发布时间】:2021-09-3023:02:38【问题描述】:在我的asp.netcore5.0应用程序中,每当我尝试使用serilo... 查看详情

如何在 asp.net core 2.1 中使用 net.tcp 服务

】如何在asp.netcore2.1中使用net.tcp服务【英文标题】:HowdoIconsumeanet.tcpserviceinasp.netcore2.1【发布时间】:2019-04-0212:26:44【问题描述】:我正在构建一个asp.netcore2.1Web应用程序,我需要调用一个旧的net.tcp端点来获取有关预订的详细信... 查看详情