【问题标题】:Why is my UserId returning a Username resulting in conversion error?为什么我的 UserId 返回用户名导致转换错误?
【发布时间】:2016-11-28 18:53:41
【问题描述】:

我正在关注本教程http://tutlane.com/tutorial/aspnet-mvc/asp-net-mvc-membership-provider-to-create-users-roles-mapping-roles-to-users

当我尝试添加角色时,我收到以下错误:

Input string was not in a correct format.

在这一行

var User = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserId));

我认为问题在于 UserId 返回的是用户名而不是用户名,但我不知道我在获取用户名方面做错了什么。

帐户控制器 RoleAddToUser

  [HttpGet]
        public ActionResult RoleAddToUser()
        {
            AssignRoleVM objvm = new AssignRoleVM(); //http://tutlane.com/tutorial/aspnet-mvc/asp-net-mvc-membership-provider-to-create-users-roles-mapping-roles-to-users
            objvm.RolesList = GetAll_Roles();
            objvm.Userlist = GetAll_Users();
            return View(objvm);
        }

   [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(AssignRoleVM objvm)
        {
            //Validation inside RoleAddtoUser ActionMethod: First validation to check both dropdownlist are select or not.
            if (objvm.RoleName == "0")
            {
                ModelState.AddModelError("RoleName", "Please select RoleName");
            }
            if (objvm.UserId == "0")
            {
                ModelState.AddModelError("UserName", "Please select Username");
            }
            if (ModelState.IsValid)
            {
                GetUserName_BY_UserID(Convert.ToInt32(objvm.UserId));
                var User = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserId));
                Roles.AddUserToRole(User, objvm.RoleName);
                ViewBag.ResultMessage = "Username added to the role successfully !";

                objvm.RolesList = GetAll_Roles();
                objvm.Userlist = GetAll_Users();
                return View(objvm);
            }
            else
            {
                objvm.RolesList = GetAll_Roles();
                objvm.Userlist = GetAll_Users();
            }
            return View(objvm);
        }

帐户控制器 GetUserName_BY_UserID

public string GetUserName_BY_UserID(int UserId)
{
    using (UsersContext context = new UsersContext())
    {
        var UserName = (from UP in context.UserProfiles
                        where UP.UserId == UserId
                        select UP.UserName).SingleOrDefault();
        return UserName;
    }
}

模型 AccountModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;

namespace AccountModule_Attempt_5.Models
{
    public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<webpages_UsersInRoles> webpages_UsersInRole { get; set; }
       // public DbSet<RegisterModel> UserProfiles { get; set; }
        //public DbSet<RegisterModel>Users { get; set; }
       // public DbSet<UsersRole> UsersRoles { get; set; }   
    }

    [Table("webpages_UsersInRoles")]
    public class webpages_UsersInRoles
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        public int RoleId { get; set; }
    }

AssignRoleVM.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace AccountModule_Attempt_5.Models
{
    public class AssignRoleVM
    {

        [Required(ErrorMessage = " Select Role Name")]
        public string RoleName { get; set; }
        [Required(ErrorMessage = "Select UserName")]
        public string UserId { get; set; }

        public List<SelectListItem> Userlist { get; set; }
        public List<SelectListItem> RolesList { get; set; }
    }
}

UserProfile.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace AccountModule_Attempt_5.Models
{
    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        [Required]
        public string UserName { get; set; }
        public string EmailId { get; set; }

        [Required]       
        public string CustomerId { get; set; }

    }

}

Roles.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AccountModule_Attempt_5.Models
{

    [Table("webpages_Roles")]
    public class Role
    {
        [Required(ErrorMessage = "Enter Role name")]
        //[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        public string RoleName { get; set; }

        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int RoleId { get; set; }
    }
}

【问题讨论】:

  • “我认为问题在于 UserId 返回的是用户名而不是 UserId”:你为什么这么认为?为什么你不确定,一种方式或另一种方式?
  • 作为旁注,命名约定中的“_”可能会在现实世界的工作环境中惹恼一些人(在这里做了很多假设,抱歉 :))
  • 嗯,我知道它正在返回用户名,因为当我尝试添加角色时,当我将鼠标悬停在 RoleAddToUser 方法中的 objvm.UserId 上时,我可以看到用户名,而不是 UserId。我不知道这是否是问题所在,因为我对此还是很陌生。
  • @JoshMcGee - 您正在将您的用户 ID 转换为 int; ASP.Net Identity 通常使用 GUID 作为 UserID - 所以尝试使用 Guid 而不是 int。 - 首先检查您的数据库,查看 UserID 类型或将鼠标悬停在调试中的 objvm.UserID 属性上,然后查看它的实际外观。
  • @Darren 我在哪里添加此代码?我尝试替换 Convert.ToInt32(objvm.UserId),但得到一个 Argument1: cannot convert from "System.Guid to 'int',如果我用这个替换整个变量,它会导致 "System.Guid to 'string' 在下一行。

标签: c# asp.net-mvc-4 asp.net-identity asp.net-roles


【解决方案1】:

问题的主要原因是您试图将字符串变量(不是数字)转换为 Int32。为了将 UserId 转换为 Int 32,它应该是数字。

此外,用户 ID 不应与数字以外的其他字符混合。

例如,如果用户 ID 是“101”,它将毫无问题地转换。但是用户 ID“Zbra101”不能转换为 Int 32。

【讨论】:

  • 谢谢。那是我的问题。 UserId 应该是数字。为什么返回用户名?当我查看我的 UserProfile 表时,我有 UserId 和 UserName。我认为这应该返回 UserId。
【解决方案2】:

你可以试试这些。 在 AccountController 中添加更改。

[HttpGet]
 public ActionResult RoleAddToUser()
{
        AssignRoleVM objvm = new AssignRoleVM(); 
        objvm.RolesList = GetAll_Roles();
        objvm.Userlist = GetAll_Users();
        return View(objvm);
}

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RoleAddToUser(AssignRoleVM objvm)
    {

        if (objvm.RoleName == "0")
        {
            ModelState.AddModelError("RoleName", "Please select RoleName");
        }
        if (objvm.UserId == "0")
        {
            ModelState.AddModelError("UserName", "Please select Username");
        }
        if (ModelState.IsValid)
        {

            var User = objvm.UserId;
            Roles.AddUserToRole(User, objvm.RoleName);
            ViewBag.ResultMessage = "Username added to the role successfully !";

            objvm.RolesList = GetAll_Roles();
            objvm.Userlist = GetAll_Users();
            return View(objvm);
        }
        else
        {
            objvm.RolesList = GetAll_Roles();
            objvm.Userlist = GetAll_Users();
        }
        return View(objvm);
    }

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 2012-11-29
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多