Reputation: 10624
I want to use Role without any provider in asp.net MVC4 project.
I success making log in and out without provider.
but for the role, I don't know how to set it up.
this is my part of AccountController.cs
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && myLogin(model.UserName, model.Password, persistCookie: model.RememberMe))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
//set Roles, how can I set role to users?
if (HttpContext.User != null)
{
if (!Roles.RoleExists("Administrator"))
{
Roles.CreateRole("Administrator");
}
Roles.AddUserToRole(model.UserName, "Administrator");
//string[] roles = { "Moderator", "Administrator" };
//HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, roles);
}
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
private bool myLogin(string userName, string password, bool persistCookie)
{
if (userName == "root" && password == "root")
{
return true;
}
else
{
return false;
}
}
the //set Roles part is not working, the error message say,
No user found was found that has the name "root". Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: No user found was found that has the name "root".
Web.config
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<roleManager enabled="true" />
I want to control accessing this page using Role check,
[Authorize(Roles="Administrator")]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
How can I define the role to user? for using filter on Action?
Upvotes: 0
Views: 1768
Reputation: 1038710
When you are calling Roles.*
you are basically calling the underlying role provider that's registered in your web.config. If you don't want to use the default role provider (which works with SQL server) you could always write a custom role provider
.
All you need to do is write a custom implementation of the RoleProvider
class, or at least the methods you intend to use:
public class MyRoleProvider: RoleProvider
{
... your implementation comes here
}
and then register your custom role provider in web.config to replace the default one:
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="MyNamespace.MyRoleProvider, MyAssembly" />
</providers>
</roleManager>
Upvotes: 4