【问题标题】:unable to assign UserID in asp.net identity to a int value type无法将 asp.net 身份中的 UserID 分配给 int 值类型
【发布时间】:2015-10-13 12:46:30
【问题描述】:

这是我的控制器动作方法-------

    public HttpResponseMessage PostPost(Post post)
    { 
     // previosly i was using simple membership to get id of logged in user
       // post.PostedBy = WebSecurity.CurrentUserId;
          post.PostedBy = User.Identity.GetUserId<int>();
           post.PostedDate = DateTime.UtcNow;
        ModelState.Remove("post.PostedBy");
        ModelState.Remove("post.PostedDate");
        if (ModelState.IsValid)
        {
            db.Posts.Add(post);
            db.SaveChanges();
   // now i am facing problem at this line. it is saying that
  //Operator '=='   cannot be applied to operands of type 'int' and 'string'  
            var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);

当我使用简单的会员资格时,我的代码工作正常。我应该尝试什么让它工作。在这里,post 是一个属性 PostedBy 为 int 的类,我想将当前的 loggedIn userId 值分配给该属性。

【问题讨论】:

  • 我喜欢你在一个问题中使用了 20 次“发布”这个词,尤其是方法签名:)
  • 哈哈哈我能做什么.....这只是一个我没有注意到@DavidG的代码

标签: c# asp.net-identity-2


【解决方案1】:

在此链接中查看答案:How to get current user, and how to use User class in MVC5?

检查答案中的代码是如何编写的:

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

如果这不起作用,请调试和跟踪代码并告诉我们 User.Identity 的值是什么?

【讨论】:

  • 我在最后一行遇到问题,它给出红色下划线,== 操作数不能应用于 int 和 string。我已经看到你提供的所有链接,但问题仍然存在
  • 对不起,我没有注意到您的代码中写的注释,好的,对于您在这里使用的数据库中的“用户”表,“ID”列的数据类型是什么?
  • Column Id是identity2.1提供的默认值。它是 int 数据类型的主键。我想获取此值并将其分配给 post 表的 PostedBy 属性。
  • 我认为它以某种方式将 Id 用作字符串,您是否可以尝试以这种方式编写最后一行并告诉我是否可行:post.PostedBy.ToString()
猜你喜欢
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多