如何使用 Dapper ORM 调用 aspnet_UsersInRoles_IsUserInRole 存储过程

How to call aspnet_UsersInRoles_IsUserInRole Stored Procedure with Dapper ORM

我需要从 Aspnet Membership.Im 调用 aspnet_UsersInRoles_IsUserInRole 像这样进行小巧的调用:

public int CheckIfUserIsInRole(IsUserInRole userInRole)
    {
        using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
        {
            DynamicParameters param = new DynamicParameters();
            param.Add("@UserName", userInRole.UserName);
            param.Add("@ApplicationName", userInRole.ApplicationName);
            param.Add("@RoleName", userInRole.RoleName);

         return    connection.Query("aspnet_UsersInRoles_IsUserInRole", param, commandType: CommandType.StoredProcedure).FirstOrDefault();               
        }
    }

在控制器中我添加:

    public int IsUserInRole(IsUserInRole isUserInRole)
    {            
        var model = _userRepository.CheckIfUserIsInRole(new IsUserInRole()
        {
            UserName = "testuser",
            RoleName = "user",
            ApplicationName = "USERMANAGEMENT"
        });

        return model;
    }

用户存在并具有正确的角色,但每次 returns 0。 这是来自 AspNet Membership 的存储过程:

ALTER PROCEDURE [dbo].[aspnet_UsersInRoles_IsUserInRole]
@ApplicationName  nvarchar(256),
@UserName         nvarchar(256),
@RoleName         nvarchar(256)

作为 开始 声明@ApplicationId 唯一标识符 SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId 来自 aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName 如果(@ApplicationId 为空) RETURN(2) 声明@UserId 唯一标识符 SELECT @UserId = NULL 声明@RoleId 唯一标识符 SELECT @RoleId = NULL

SELECT  @UserId = UserId
FROM    dbo.aspnet_Users
WHERE   LoweredUserName = LOWER(@UserName) AND ApplicationId = @ApplicationId

IF (@UserId IS NULL)
    RETURN(2)

SELECT  @RoleId = RoleId
FROM    dbo.aspnet_Roles
WHERE   LoweredRoleName = LOWER(@RoleName) AND ApplicationId = @ApplicationId

IF (@RoleId IS NULL)
    RETURN(3)

IF (EXISTS( SELECT * FROM dbo.aspnet_UsersInRoles WHERE  UserId = @UserId AND RoleId = @RoleId))
    RETURN(1)
ELSE
    RETURN(0)

结束

我哪里弄错了? 有什么解决方法的建议吗?

我需要这个存储过程来检查用户是否在那个角色中,所以我可以将它用于 [AuthorizeRoles("RoleTest")]

该存储过程没有return任何记录;它使用 return 值代替。这个需要作为参数处理:

public int CheckIfUserIsInRole(IsUserInRole userInRole)
{
    using (var connection = new SqlConnection(ConfigurationSettings.GetConnectionString()))
    {
        DynamicParameters param = new DynamicParameters();
        param.Add("@UserName", userInRole.UserName);
        param.Add("@ApplicationName", userInRole.ApplicationName);
        param.Add("@RoleName", userInRole.RoleName);
        param.Add("@ReturnValue", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

        connection.Execute("aspnet_UsersInRoles_IsUserInRole", param, commandType: CommandType.StoredProcedure);

        return param.Get<int>("@ReturnValue");
    }
}

https://github.com/StackExchange/dapper-dot-net#stored-procedures

(也发布到 your copy of this question on CodeProject。)