你知道为什么会这样吗:
public struct UserNameAndPassword { public string username; public string password; } [HttpPost] public IActionResult Create([FromBody]UserNameAndPassword usernameAndPassword) { Console.WriteLine(usernameAndPassword); if (this.AuthenticationService.IsValidUserAndPasswordCombination(usernameAndPassword.username,usernameAndPassword.password)) return new ObjectResult(Generatetoken(usernameAndPassword.username)); return BadRequest(); }
但是当我用元组替换它时,这不起作用?
[HttpPost] public IActionResult Create([FromBody](string username,string password) usernameAndPassword) //encrypt password? { Console.WriteLine(usernameAndPassword); if (this.AuthenticationService.IsValidUserAndPasswordCombination(usernameAndPassword.username,usernameAndPassword.password)) return new ObjectResult(Generatetoken(usernameAndPassword.username)); return BadRequest(); }
usernameAndPassword.username和.password都为null.
你不被允许在控制器中使用元组吗?
解决方法
它不起作用,因为命名的元组名称不是很“真实”,它主要是由编译器提供的语法糖.如果您查看ValueTuple类型集,通过它们表示命名元组,您将看到它们具有Item1,Item2等属性.
编译器会将对命名元组名称的所有引用重写为它们的真实名称(Item1等).例如,你有这个:
static void Create((string username,string password) usernameAndPassword) { Console.WriteLine(usernameAndPassword.username); Console.WriteLine(usernameAndPassword.password); }
但是当你编译它时,你真正拥有的是:
static void Create([TupleElementNames(new string[] {"username","password"})] ValueTuple<string,string> usernameAndPassword) { Console.WriteLine(usernameAndPassword.Item1); Console.WriteLine(usernameAndPassword.Item2); }
您的名称现在仅在元数据属性TupleElementNames中,但不在代码中.
出于这个原因,当你发布类似的东西:
{"username": "x","password": "y"}
对你的行动,asp.net无法绑定.但如果你发布:
{"item1": "x","item2": "y"}
然后它会没有任何问题.您可以编写自定义绑定器,它可以使用TupleElementNames属性,但没有理由真的.只需使用评论中建议的单独参数或实际模型.你的动作输入参数并不是一件容易的事.您可能稍后想要验证它们,从模型生成文档等等.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。