加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

在ASP.NET Core Web API Controller中使用C#7元组

发布时间:2020-12-16 07:13:34 所属栏目:asp.Net 来源:网络整理
导读:你知道为什么会这样吗: public struct UserNameAndPassword { public string username; public string password; } [HttpPost] public IActionResult Create([FromBody]UserNameAndPassword usernameAndPassword) { Console.WriteLine(usernameAndPassword)
你知道为什么会这样吗:

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属性,但没有理由真的.只需使用评论中建议的单独参数或实际模型.你的动作输入参数并不是一件容易的事.您可能稍后想要验证它们,从模型生成文档等等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读