I was trying to let the accountController to assign roles to each newly registered user automatically, so I've ended up doing something like this:
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
//there is where the error is being raised.
await _userManager.AddToRoleAsync(user, "testRole");
if (result.Succeeded)
{
//here goes some code
//have also adding this line of code inside this if stmt
//await _userManager.AddToRoleAsync(user, "testRole");
}
AddErrors(result);
}
return View(model);
}
I did what other posts on StackOverFlow recommended but, I keep having this error:
InvalidOperationException: Role TESTROLE does not exist.
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore+d__34.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
Microsoft.AspNetCore.Identity.UserManager+d__104.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) System.Runtime.CompilerServices.TaskAwaiter.GetResult()
WebApplication2.Controllers.AccountController+d__17.MoveNext()
in AccountController.cs
Notes:
I was using PostgreSql on my project, so I've created a new project
with MSSQL and ended up with the same error.
I've made sure that the testRole is being in the table AspNetRoles. So ,there's no problem with that either!
so testRole is exact name which would then get normalized to TESTROLE how was TestRole created? I say this because Identity looks for the normalized version. Exception is pretty clear that it doesn't exist in this case. Basically if you didn't use RoleManager then something is wrong with the way you created the role
Another way to create the role would be using your database context and add in new roles that way but if you didn't use caps for the NormalizedName field entry then this is the error you will get
Related
I init a User info table only not have FacebookID column, and there were 2 record. Now I add a FacebookID column to practice register by Facebook using migration EF core Framework. In first called, a record added and 2 FacebookID under is null. And I want to second called, It have to check that FacebookID is exist, If it is exist, please return message that FacebookID is exist. If it is not exist, add new User
I wrote a function to check that, because 2 Facebookid in image is null so It not working
RuleFor(model => model).MustAsync((x, cancellationToken) => FacebookIdMustUnique(x.FacebookId, cancellationToken))
.WithMessage(string.Format(Resource.Validation_Existed, Resource.FacebookId));
async Task<bool> FacebookIdMustUnique(string facebookId, CancellationToken cancellationToken = default(CancellationToken))
{
var user = await userService.GetAsync(x =>
x.FacebookId.Equals(facebookId, StringComparison.InvariantCultureIgnoreCase),
cancellationToken
);
return user == null;
}
image description here
I wrote a function to check that, because 2 Facebookid in image is null so It not working
Your following code will throw in this line when the Facebookid is null :
x.FacebookId.Equals(facebookId, StringComparison.InvariantCultureIgnoreCase)
To fix it, you need take consideration whether it is null before invoke its .Equals() method:
async Task FacebookIdMustUnique(string facebookId, CancellationToken cancellationToken = default(CancellationToken))
{
if(facebookId ==null){ return true; }
var user = await userService.GetAsync(
x => x.FacebookId.Equals(facebookId, StringComparison.InvariantCultureIgnoreCase),
cancellationToken
);
return user == null;
}
(In your case, it likely be fine if the facebook id is null, so I just return true)
As a reminder: it' always a good practice to check null for Nullable types.
I have a ASP.NET MVC web application and I want to register and login using angular. I'm calling a Login and Register Method on my WebAPI when the user wants to Login/Register. The problem is that I don't know how to transfer my MVC Login and Register in the AccountController to my WebAPI.
My current Register method looks like this:
// POST api/RegisterApi
public async Task<HttpResponseMessage> Post([FromBody]RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return await this.BadRequest(this.ModelState).ExecuteAsync(new CancellationToken());
}
var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email
};
IdentityResult result = await this.UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return await this.GetErrorResult(result).ExecuteAsync(new CancellationToken());
}
// Auto login after register (successful user registration should return access_token)
var loginResult = this.LoginUser(new LoginViewModel()
{
Email = model.Email,
Password = model.Password
});
return await loginResult;
}
My main issue is the following line:
IdentityResult result = await this.UserManager.CreateAsync(user, model.Password);
Somehow i can't call the CreateAsync-Method and I don't really know why.
I get the following error:
Task' does not contain a definition for 'CreateAsync'
and no extension method 'CreateAsync' accepting a first argument of
type 'Task
Do you guys can give my any input on doing this properly? Everything I've seen so far seemed far too complicated for my problem.
EDIT: Okay the error is solved, but now there's a new problem. The CreateAsync method does not Create a User and returns to the error function in my AngularJs. Do you guys have any suggestion why CreateAsync could fail?
I am trying to create a user by calling register function within the application.
This function works fine when the function is called as a API.
When Called from Inside the application it throws an error
AccountController ac = new AccountController();
RegisterBindingModel rbm = new RegisterBindingModel();
rbm.Email = UserAccountBase.Email;
rbm.Password = "TestPassword";
rbm.ConfirmPassword = "TestPassword";
var userId = await ac.Register(rbm);
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
try
{
var result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
catch(Exception e) {
var message = e.Message;
}
return Ok(user.Id);
}
UserManager.CreateAsync Throws an error
Value cannot be null. Parameter name: request
Did you build this using ASP Identity 2.0 and EF Code First? If so, check to see if your initial DB configuration put a column called 'Discriminator' at the end of AspNetUsers. If this is the case, recreate an initial migration and remove that column that gets generated. Once removed, you can perform an update-database. Does this make any sense? I just had this happen to me.
In the identity model, you will have a Discriminator column. In your model, add migration and update the database.
I am new to asp.net. I am trying to create a simple login and register webpage with WebMatrix. But I get the following error when I try to create an account:
The Provider encountered an unknown error.
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.Web.Security.MembershipCreateUserException: The Provider encountered an unknown error.
Source Error:
Line 32: db.Execute("INSERT INTO UserData (Email,Name) VALUES (#0,#1)", email, username);
Line 33:
Line 34: WebSecurity.CreateAccount(email,password);
Line 35: Response.Redirect("Homepage.cshtml");
Line 36: }
Source File: c:\Users\admin\Documents\My Web Sites\Login\Register.cshtml Line: 34
Stack Trace:
[MembershipCreateUserException: The Provider encountered an unknown error.]
WebMatrix.WebData.SimpleMembershipProvider.CreateAccount(String userName, String password, Boolean requireConfirmationToken) +1312
WebMatrix.WebData.WebSecurity.CreateAccount(String userName, String password, Boolean requireConfirmationToken) +31
ASP._Page_Register_cshtml.Execute() in c:\Users\admin\Documents\My Web Sites\Login\Register.cshtml:34
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +68
System.Web.WebPages.WebPage.ExecutePageHierarchy() +156
System.Web.WebPages.StartPage.RunPage() +19
System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase httpContext) +119
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
Any help is appreciated. Thanks.
I just had the same issue ... I was using
WebSecurity.CreateAccount(model.UserName, model.Password);
and above generated issue ..
then I tried:
WebSecurity.CreateAccountAndUser(model.UserName, model.Password);
and find out that I was missing other required fields of my Users table (UserProfile). Following worked for me:
WebSecurity.CreateAccountAndUser(model.UserName, model.Password, new {RequiredColumn1 = Value1, RequiredColumn2 = Value 2, ...... });
The post is old, but hope this can help others..
Be sure to:
Create the User record first
Invoke WebMatrix to create the User account.
Below is my code which resolved the same issue you're having:
public ActionResult SignUp(SignUpModel model)
{
if (ModelState.IsValid)
{
using (MorphometryContext context = new MorphometryContext())
{
User user = new User
{
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
Username = model.UserName
};
context.Users.Add(user);
context.SaveChanges();
}
// Attempt to register the user
try
{
WebSecurity.CreateAccount(model.UserName, model.Password);
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
return View();
}
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Projects");
}
Also, you don't want to Respoonse.Redirect to a .cshtml file. Instead you should return a RedirectToAction and pass in the Action and Controller names.
I've just had this problem - but by your code it might not be the same thing. I was trying to create the membership record before creating the record in my own user table. It has to be the other way round.
So I'd check that your INSERT INTO UserData query was actually working.
In my case; It was because of Culture;
the Membership provider for creating account with CreateUserAndAccount function, first create a user. it is ok for now, and the user successfully added to the Database.
But for creating account, It runs the below query to get userID to create new account for it:
SELECT [userID] from [User] Where (UPPER([userName]) = #0);
Here is where exception thrown because in some culture upper casing the letters is different, for example in turkish, the upper case for 'i' is 'İ'.
I Don't know how to solve this problem for this moment, and I'll try to learn it.
In my case I was creating a user named "admin" and exception throw. I change the user name to "mesut" And it runs successfully.
please make sure if you have a culture specific letters in userName field.(or email in your case), (as soon as I found how to solve it I will post it here)
In my MasterPage code-behind I try to get UserID of the authenticated (if it has) one:
public Guid CurrentUserID
{
get
{
Guid userID = new Guid();
if (Context.User.Identity.IsAuthenticated)
{
MembershipUser user = Membership.GetUser(Context.User.Identity.Name);
userID = (Guid)user.ProviderUserKey;
}
return userID;
}
}
Once the error "Object reference not set to an instance of an object" appeared. I suspect the problem is in the case Context.User=null. Could it be the reason?
Maybe the user was deleted by the db while he was authenticated, so Membership.GetUser returned null and user.ProviderUserKey has thrown NullReferenceException.