在asp.net中string username = reader.GetString(0).Trim();是啥意思

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在asp.net中string username = reader.GetString(0).Trim();是啥意思相关的知识,希望对你有一定的参考价值。

参考技术A 获取你查询的对象的第一列值··并赋值给username 参考技术B 这个 reader 应该是个 DATAREADER 吧……
读数据库的对象吧
.GetString(0) 取第一列数据 trim() 取出首尾空格
参考技术C 给username 赋值

reader.GetString(0)获取reader中的第一个记录

Trim() 去掉两端空格

如何在 asp.net 中将“int”转换为“string”

【中文标题】如何在 asp.net 中将“int”转换为“string”【英文标题】:How to convert from 'int' to 'string' in asp.net 【发布时间】:2017-03-19 01:16:42 【问题描述】:

这是我的登录代码:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    
        if (!ModelState.IsValid)
        
            return View(model);
        
        var user = UserManager.FindByNameAsync(model.UserName);
       var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        
            case SignInStatus.Success:
                if (returnUrl != null)
                    return RedirectToLocal(returnUrl);
                else if (await UserManager.IsInRoleAsync(user.Id, "Admin")) //<= Checking Role and redirecting accordingly.
                    return Redirect("~/Admin/Home/");
                else
                    return Redirect("~/User/Home");
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new  ReturnUrl = returnUrl, RememberMe = model.RememberMe );
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        
    

但它告诉我这个错误:

论据 1:无法从 'int' 转换为 'string' GoKhoda

在这一行显示错误:

 else if (await UserManager.IsInRoleAsync(user.Id, "Admin"))

此行用于查找用户和用户角色以重定向到页面。

我该如何解决这个问题?

编辑

public class ApplicationUserManager : UserManager<ApplicationUser>

    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    
    

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        ;

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        ;

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        
            MessageFormat = "Your security code is 0"
        );
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        
            Subject = "Security Code",
            BodyFormat = "Your security code is 0"
        );
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        
        return manager;
    

编辑(2)

当我使用.TosString() 时,显示此错误。

【问题讨论】:

使用“ToString()”方法将int转换为字符串。 Try else if (await UserManager.IsInRoleAsync(user.Id.ToString(), "Admin")), 可能你的TKey是字符串类型 user.Id 中存储了什么?它是 guid 还是 int? @vipin 我用过。但它不起作用。 我认为您的错误与转换为字符串没有任何关系,并且发生在 UserManager.IsInRoleAsync 内。所以首先我会检查user.id 中是否有任何值(放置一个断点并单步执行您的代码)。那么,如果 user.id 有值,您能否发布您的 UserManager.IsInRoleAsync 方法的代码。 【参考方案1】:

恕我直言,您的错误不仅仅是intString 的转换,它与FindByNameAsync 方法有关。当 UserId 属性请求 IsInRoleAsync 方法但 ApplicationUser 类中不存在该属性时会出现问题(与 Dapper 映射问题有关)。

根据MVC - InvalidOperationException: UserId not found,确保FindByNameAsync 像这样在ApplicationUser 中包含Id 属性(如果有,请使用您的EF 数据库上下文而不是查询语句):

public async Task<ApplicationUser> FindByNameAsync(string userName)

    ApplicationUser result = null;
    using (var conn = await GetOpenDBConnection())
    
        try
        
            // note that UserId does not exist on ApplicationUser by default
            // thus we need to adjust the query statement
            var queryResults = await conn.QueryAsync<ApplicationUser>(
                "SELECT UserId AS [Id], UserName, Email FROM dbo.Users WHERE UserName = @UserName;",
                new  UserName = userName );

            result = queryResults.FirstOrDefault();
        
        catch (Exception ex)
        
            // handle exception
        
    
    return result;

您也可以尝试FindByName 方法,而不是那里的FindByNameAsync

关于await 使用错误,异常说明在给定上下文中一次只允许一个异步操作(请参阅Multi-async in Entity Framework 6?),因此您需要将await 移到if 条件之外或创建一个新上下文在执行第二个await之前:

var isInRole = await UserManager.IsInRoleAsync(user.Id.ToString(), "Admin");

// inside switch...case
if (returnUrl != null)
     return RedirectToLocal(returnUrl);
else if (isInRole) //<= Checking Role and redirecting accordingly.
     return Redirect("~/Admin/Home/");
else
     return Redirect("~/User/Home");

如果仍然抛出异常,则更改为IsInRole

if (returnUrl != null)
    return RedirectToLocal(returnUrl);
else if (UserManager.IsInRole(user.Id.ToString(), "Admin")) //<= Checking Role and redirecting accordingly.
    return Redirect("~/Admin/Home/");
else
    return Redirect("~/User/Home");

这可能会或可能不会解决您的整个问题,但可以解释您应该如何处理与异步相关的问题。

相关问题:

MVC InvalidOperationException adding role to user

Manually Map column names with class properties

Entity framework async issues context or query?

【讨论】:

以上是关于在asp.net中string username = reader.GetString(0).Trim();是啥意思的主要内容,如果未能解决你的问题,请参考以下文章

asp.net mvc3 返回多个json列表

如何在 ASP.NET 中使用 <label> 标签?

在 asp.net 核心上使用 Dapper 插入

asp.net 如何获得 当前用户 userid

C# asp.net 数据库操作

ASP.NET Security