Spring请求参数缺失:C#客户端传参时firstName、lastName未被Java服务端接收
问题根因
核心原因是HTTP请求参数名大小写不匹配,Spring MVC的@RequestParam默认对参数名大小写敏感:
- C#代码构造请求URL时,拼接的两个参数名为
firstname、lastname(name的n为小写) - Java接口
@RequestParam声明需要接收的参数名为firstName、lastName(Name的N为大写)
username、password的参数名两边拼写完全一致,所以可以正常接收。
解决方案
以下两种方案二选一即可:
- 修改C#端的请求参数名,和Java端声明保持一致
调整C#代码中请求URL的参数部分:
public async Task<User> RegisterUserAsync(string username, string password, string firstName, string lastName) { Console.WriteLine("Registering..."); // 仅修改参数名firstname为firstName、lastname为lastName即可 HttpResponseMessage responseMessage = await Client.GetAsync($"http://localhost:8080/user/register?username={username}&password={password}&firstName={firstName}&lastName={lastName}"); if (responseMessage.StatusCode == HttpStatusCode.OK) { string userAsJson = await responseMessage.Content.ReadAsStringAsync(); User resultUser = JsonSerializer.Deserialize<User>(userAsJson); Console.WriteLine("Registered"); return resultUser; } throw new Exception("User could not be registered"); }
- 修改Java端的
@RequestParam注解,显式指定接收的参数名和C#端传的一致
调整Java接口的参数注解:
@GetMapping("/register") public ResponseEntity<User> ValidateRegister( @RequestParam String username, @RequestParam String password, @RequestParam("firstname") String firstName, @RequestParam("lastname") String lastName) { try{ System.out.println(username); User user = userService.ValidateRegister(username,password,firstName,lastName); if(user == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(user); } catch (Exception e) { System.out.println(e.getMessage()); return ResponseEntity.badRequest().build(); } }
补充建议
注册接口使用GET请求存在安全风险,账号密码会明文出现在URL、服务器日志、代理记录中,建议改为POST请求,参数放在请求体中传输。
内容的提问来源于stack exchange,提问作者Lukas Juskevicius
相关产品推荐
相关产品推荐

