0

我设计了一个带有列的数据库user_id。现在在登录后的表单页面中,当我单击插入按钮时,我需要user_id填写HttpContext.Current.User.Identity.Name

但它告诉我一个错误。我转换为 int.parse 或 string 或者我只是使用了HttpContext.Current.User.Identity仍然错误。谁能帮我?

例如

cmd.Parameters.AddWithValue("user_id", HttpContext.Current.User.Identity);

我应该补充一点,我的user_id列属于intSQL Server 2008 中的数据类型。

它说我它是IConvertible并且根本无法转换.. 不是stringor int

那么登录后如何填写user_iddb呢?

4

1 回答 1

1

这不起作用有几个原因:

cmd.parameters.addwithvalue("user_id".httpcontext.current.user.identity");
  1. 它不会编译 -注意:请在将来的示例中包含可编译的代码。
  2. Identity这是一个IIdentity. 这不会转换为int.
  3. 用户 ID不存储,也不可用IPrincipal

您需要通过往返数据库来恢复用户 ID。您唯一可以使用的是HttpContext.Current.User.Identity.Name.


现在,我过去所做的是在我的UserProfile模型中添加一个方法,你知道,提供者在调用它时使用该方法来实际创建用户记录:

WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
    new
    {
        // additional profile fields are passed as an anonymous type
        CustomField1 = model.CustomField1
    });

这是UserProfile方法:

public static int? PrincipalUserId(IPrincipal user)
{
    if (!user.Identity.IsAuthenticated)
    {
        return null;
    }

    var key = string.Format("userid_{0}", user.Identity.Name);

    int userId;
    if (!SharedCacheManager.TryGetValue<int>(key, out userId))
    {
        using (UsersContext udb = new UsersContext())
        {
            userId = udb.UserProfiles
                .Where(up => up.UserName == user.Identity.Name)
                .First().UserId;
        }

        SharedCacheManager.SetValue<int>(key, userId);
    }

    return userId;
}

这是SharedCacheManager

public static class SharedCacheManager
{
    public static bool TryGetValue<T>(string key, out T result)
    {
        var cache = HttpContext.Current.Cache;

        object o = cache[key];
        if (o == null)
        {
            result = default(T);
            return false;
        }
        else if (o.GetType() != typeof(T))
        {
            result = default(T);
            return false;
        }

        result = (T)o;
        return true;
    }

    public static void SetValue<T>(string key, T val)
    {
        var cache = HttpContext.Current.Cache;
        cache[key] = val;
    }
}

现在,所有这些代码都不会直接放入您的解决方案中。但它可以很容易地修改。

于 2013-10-31T08:50:54.693 回答