Ich versuche, Aspnet mit Rollen zu verwenden. Mit der NRE kann ich immer noch nicht herausfinden, was zu instantiieren ist. Dies ist in der SteuerungObjektreferenz wird nicht auf eine Instanz eines Objekts gesetzt, wenn Autorisierung mit Rollen verwendet wird
[Authorize(Roles = "Admin")]
public ActionResult ForAdmin()
{
return View();
}
Dies ist, wie ich
public Programmer GetLoginCredentials(Login credential)
{
Programmer programmer = null;
HttpContext.Current.Session["ProgrammerName"] = null;
HttpContext.Current.Session["Roles"] = null;
using (
var cmd = new SqlCommand("Sp_GetLoginCredentials", _dbConnection)
{
CommandType = CommandType.StoredProcedure
})
{
try
{
cmd.Parameters.AddWithValue("@Username", credential.Username);
cmd.Parameters.AddWithValue("@Password", credential.Password);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count <= 0) return null;
foreach (DataRow row in ds.Tables[0].Rows)
{
programmer = new Programmer()
{
ProgrammerId = Convert.ToInt32(row["ProgrammerId"]),
ProgrammerName = row["ProgrammerName"].ToString(),
Username = row["Username"].ToString(),
Password = row["Password"].ToString()
};
HttpContext.Current.Session["ProgrammerName"] = programmer.ProgrammerName;
}
if (programmer != null)
{
GetRoles(programmer);
}
return programmer;
}
catch
{
return null;
}
}
}
autorisieren Dies ist, wie ich die Sitzung mit Rollen
public List<Role> GetRoles(Programmer credential)
{
var roleList = new List<Role>();
using (var cmd = new SqlCommand("Sp_GetRoles", _dbConnection) {CommandType = CommandType.StoredProcedure})
{
cmd.Parameters.AddWithValue("@Username", credential.Username);
cmd.Parameters.AddWithValue("@Password", credential.Password);
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
roleList.AddRange(from DataRow row in ds.Tables[0].Rows
select new Role()
{
RoleName = row["RoleName"].ToString()
});
}
HttpContext.Current.Session["Roles"] = roleList;
}
return roleList;
}
Diese füllen ist mein Rollenanbieter
public class SiteRole : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
var data = HttpContext.Current.Session["Roles"];
return data as string[];
}
}
In meiner Session [ „Rollen“] ich es wie diese
Das heißt also, ich bin in der Lage, die „Admin“ Rolle zu bekommen, aber in meinem Browser, bekomme ich diesen Fehler:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Security.RolePrincipal.IsInRole(String role) +9803940
System.Linq.Enumerable.Any(IEnumerable`1 source, Func`2 predicate) +146
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +333
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +379
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +143
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +446
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Kannst du mir bitte zeigen, wo ich falsch liege? Vielen Dank.
Ich empfehle gegen Berechtigungszustand und den Sitzungszustand zu mischen. Die meisten Authentifizierungs-/Autorisierungs-Frameworks verfügen bereits über eingebaute Mechanismen für das Behalten von Rollen und das Abrufen dieser Rollen basierend auf dem Authentifizierungstoken. Verwenden Sie diese und versuchen Sie nicht, diese Informationen im Sitzungszustand zu speichern, in den sie nicht gehören. Wenn Sie weitere Hilfe benötigen, sollten Sie die Details für Ihre Authentifizierungseinrichtung angeben. – Igor
Mögliches Duplikat von [Was ist eine NullReferenceException und wie behebe ich sie?] (Https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Igor
Danke Igor. Ich werde meinen Code ändern, um zu reflektieren, was Sie empfohlen haben. Gibt es eine Möglichkeit, die Signatur von "public override string [] GetRolesForUser (string username)" zu ändern, so dass es 2 Parameter erhält, um den Benutzernamen und das String-Passwort zu string? –