Error using Role Based authentication in MVC application

M J 661 Reputation points
2024-02-11T18:28:33.5533333+00:00

I have an MVC application using the .Net framework that uses Authentication with individual user accounts.
Everything works great.
I am able to register new users and login with them. CRUD operations work on all of my models. Then I wanted to add some role based authentication. I have 2 roles, Visitor and Admin. Users will be automatically assigned the visitor role when they register. I have written a method for the admin users to search all users for an email and assign that person to Admin role. Then I added this to my _Layout.cshtml file

if (User.IsInRole("Admin"))
{
    <li>@Html.ActionLink("Admin Menu", "Index", "Main", new { area = "Admin"},null)</li>
}

I build and run. At which time it threw an error pointing to that line, saying it could not find the Sql Server Express database. I don't use Sql Server Express. Why isn't it using the connection string listed in my Web.config file? Here is the relevant part of my Web.config file

 <connectionStrings>
    <add name="DefaultConnection" 
connectionString="Data Source=DESKTOP-6HOPM3U;Initial Catalog=MoveMyTub;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
providerName="System.Data.SqlClient" />
  </connectionStrings>

Is there something in Identity.Config that I need to find and change so that it uses the default connection string and doesn't look for some non-existant Sql Server Express version?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,494 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Sakthivel Ganesan 0 Reputation points
    2024-02-12T17:12:59.38+00:00

    Hi, Could you try adding the below config and see if it works?

    <system.web>
        <roleManager>
            <providers>
                <clear/>
                <add name="AspNetSqlRoleProvider" connectionStringName="<your connection string name here>" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
            </providers>
        </roleManager>
    </system.web>
    
    

  2. SurferOnWww 2,906 Reputation points
    2024-02-13T02:04:19.5366667+00:00

    I guess that you created the MVC4 application with the Forms Authentication of  SimpleMembershipProvider by using the Internet Application template of Visual Studio 2010.

    Did you add the roles? If yes, you can see the added roles in the SQL Server database, as shown below; role

    If not, you will have to add the action methods and views which are used to create, delete and assign the roles. For details, please see the following article:

    Working with Roles in ASP.NET MVC 4+


  3. M J 661 Reputation points
    2024-02-13T17:05:30.6333333+00:00

    Resolved by adding the following Added to Web.config appSettings section

    <add key="enableSimpleMembership" value="false"/>    
    <add key="autoFormsAuthentication" value="false"/>
    
    

    added to Web.confiig web.settings section

    <authentication mode="Forms">
          <forms loginUrl="Account/Login" />
        </authentication>
        <roleManager defaultProvider="userRoleProvider" enabled="true">
          <providers>
            <clear/>
            <add name="userRoleProvider" type="MoveMyTub.Models.UserRoleProvider" />
          </providers>
        </roleManager>
    

    added this class

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    namespace MoveMyTub.Models
    {
        public class UserRoleProvider:RoleProvider
        {
            public override string ApplicationName
            {
                get
                {
                    throw new NotImplementedException();
                }
                set
                {
                    throw new NotImplementedException();
                }
            }
            public override void AddUsersToRoles(string[] usernames, string[] roleNames)
            {
                throw new NotImplementedException();
            }
            public override void CreateRole(string roleName)
            {
                throw new NotImplementedException();
            }
            public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
            {
                throw new NotImplementedException();
            }
            public override string[] FindUsersInRole(string roleName, string usernameToMatch)
            {
                throw new NotImplementedException();
            }
            public override string[] GetAllRoles()
            {
                throw new NotImplementedException();
            }
            public override string[] GetRolesForUser(string Id)
            {
                using (SqlConnection oConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
                {
                    using (SqlCommand oCmd = new SqlCommand())
                    {
                        try
                        {
                            oCmd.CommandText = "ListUserRoles";
                            oCmd.CommandType = CommandType.StoredProcedure;
                            oCmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = Id;
                            oCmd.Connection = oConn;
                            oConn.Open();
                            using (SqlDataReader rdr = oCmd.ExecuteReader())
                            {
                                List<RoleName> roleList = new List<RoleName>();
                                while (rdr.Read())
                                {
                                    RoleName role = new RoleName
                                    {
                                        Name = rdr[1].ToString()
                                    };
                                    roleList.Add(role);
                                }
                                string[] userRoles = roleList.Select(x=> x.ToString()).ToArray();
                                return userRoles;
                            }
                        }
                        catch (Exception ex)
                        {
                            Errors.ErrorOccured(ex, "Id = " + Id);
                            return null;
                        }
                        finally
                        {
                            oCmd.Dispose();
                            oConn.Close();
                        }
                    }
                }
            }
            public override string[] GetUsersInRole(string roleName)
            {
                throw new NotImplementedException();
            }
            public override bool IsUserInRole(string username, string roleName)
            {
                throw new NotImplementedException();
            }
            public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
            {
                throw new NotImplementedException();
            }
               
            public override bool RoleExists(string roleName)
            {
                throw new NotImplementedException();
            }  
        }
    }
    

    Now it works

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.