【问题标题】:How to retrieve the current user ID如何检索当前用户 ID
【发布时间】:2015-01-20 18:09:39
【问题描述】:

我正在制作相册。所以,我想要一张属于某个用户的照片。如何获取用户 ID?

var com = new SqlCommand("Insert into Photos (Photo, DatePublished, UserId)" +
    "values (@Photo, @DatePublished, @UserId)", con);
com.Parameters.AddWithValue("@Photo", pic);
com.Parameters.AddWithValue("@DatePublished", DateTime.Today);
com.Parameters.AddWithValue("@UserId", //what should be written here?);
con.Open();
com.ExecuteNonQuery();
lblStatus.Text = "Image Uploaded Sucessfully";

或者你能指出一些其他的方式来实现这种归属感吗?谢谢。

【问题讨论】:

  • 您是否将 UserId 列定义为 IDENTITY 列?
  • 你使用的是ASP.Net Identity、Membership Provider等Membership吗?
  • 如果这是一个 Web 应用程序,您可以轻松获取用户名,如果 UserId 列是字符串,您可以轻松获取用户名,并将其拆分为获取用户名。如果不是,那么您需要做一个额外的查询,查询该数据库并根据使用User.Identity.Name 登录的用户名返回用户ID,同时查看PrincipalContext UserPrincipal
  • @Steve,我做到了。但问题是这个表将 UserId 声明为外键,而外键又与名为“Users”的表有关系。后者有一个 IDENTITY 列 UserId。
  • @MethodMan,非常感谢!

标签: c# asp.net visual-studio web


【解决方案1】:

希望您的用户先登录 :)

假设您这样做了,那时您应该在执行 SELECT 以检查他们的凭据时将他们的 ID 存储在内存中。只需检索该值并将其用于此查询。

//Global state is a made up static class of course
com.Parameters.AddWithValue("@UserId", GlobalState.CurrentUserId);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2020-08-27
    相关资源
    最近更新 更多