English 中文(简体)
如何从 asp. net mvc3 的成员数据库中检索用户 Id?
原标题:How to retrieve user Id from membership database in asp.net mvc3?

我用 reg_sql 创建了一个数据库, 并将其添加到我的项目数据库中, 供成员使用 。 现在我需要访问登录到用户编号 。 简单地说, 我想显示它, 以查看 doditwrk 是否 。 我用这个代码来连接器中的函数 :

  var id = from ad in StoreDb.aspnet_Users where
  StoreDb.aspnet_Users.Name == System.Web.HttpContext.Current.User.Identity.Name 
  select ad.UserId;
  ViewBag.Message = id;

但是在我看来,我看到了这一点:

系统. Data. Obbjects. 目标查询 '1 [系统. 指南]

What shoud I do to retrieve User Id??? Thanks

最佳回答

在此设置一个函数,您可以将该函数投放到控制器中,然后在获取 ID 的动作中使用该函数。当服务提供方给您一个 API 来查询成员资格数据库时,无需做所有代码即可查询该数据库。

private Guid GetUserID() {
    var currentUser = Membership.GetUser(User.Identity.Name);
    var userID = (Guid)currentUser.ProviderUserKey;
    return userID;
}

public ActionResult Index() {
    var userID = GetUserID();
    ...
}

您也可以将该代码放入一个基本控制器, 这样您就可以从继承该代码的任何控制器中获取该函数。 这样可以保留您的代码 DRY( 重覆您自己), 这样您就不会有代码重复 。

用法将是

创建基地控制器, 并将其放置在 主计长 下称为 base 的文件夹

namespace YourApp.Web.Controllers {
    public abstract class MyBaseController : Controller {

        protected Guid GetUserID() {
            var currentUser = Membership.GetUser(User.Identity.Name);
            var userID = (Guid)currentUser.ProviderUserKey;
            return userID;
        }
    }
}

现在您可以通过继承该控制器来在您的任何常规控制器中使用该控制器 。

public class HomeController : MyBaseController {

    public ActionResult Index() {
        var userID = GetUserID();
        ...
    }
}
问题回答

var id 代表 ObjectQuery<System.Guid> 您必须分析查询结果, 例如 :

foreach (Guid result in id)
  Console.WriteLine("UserID: {0}", result.ToString());




相关问题
IEnumerable to array of parameter

Using linq? and XML is there a way to convert this IEnumerable to a string array of the value parameter? List<string> idList = new List<string>(); foreach (XElement idElement in word....

linq query for tag system - search for multiple tags

I have two tables, Tags(tagid, postid, tagname) and posts(postid, name, ...) now i want to make a query that returns me all posts that have a generic amount of tags. like: i want all posts that have ...

Linq operations against a List of Hashtables?

I m working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

How to filter duplicate list items

i have list of items IList with data that looks list this: GenId TestMode 1 0 1 1 3 0 3 1 4 NULL 2 NULL i want to remove the index ...

C# Grouping/Sorting a Generic List<> using LINQ

Im looking to group and sort a Generic List<>. I have a list of objects representing files and each of these objects has a FileName, FileType and FileDate property. FileType is defined as an ...

热门标签