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

时间:2016-11-05 06:58:04

标签: asp.net asp.net-mvc asp.net-identity identity

这是我的登录代码:

int main() {
  initscr();
  noecho();
  curs_set(0);

  int flag = fork();
  if (flag == -1)
    exit(1);
  else if (flag == 0) {
    WINDOW *win = newwin(4, 4, 0, 0);
    int n = 0;
    while (1) {
      mvwprintw(win, 0, 0, "%d", n % 9);
      wrefresh(win);
      n = (n + 1) % 9;
      sleep(1);
    }
  }
  else {
    WINDOW *win = newwin(4, 4, 8, 8);
    int n = 0;
    while (1) {
      mvwprintw(win, 0, 0, "%d", n % 9);
      wrefresh(win);
      n = (n + 1) % 9;
      sleep(1);
    }
  }
  endwin();

  return 0;
}

但是它显示了这个错误:

  

参数1:无法从'int'转换为'string'GoKhoda

在此行中显示错误:

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);
        }
    }

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

我该如何解决这个问题?

修改

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

修改(2)

当我使用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; } } 时显示此错误。

enter image description here

1 个答案:

答案 0 :(得分:2)

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

根据MVC - InvalidOperationException: UserId not found,确保FindByNameAsync在此Id中包含ApplicationUser属性(如果您拥有它而不是查询语句,请使用您的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移到外面在执行第二个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?