Compare Email Address entered to database with DataAnnotations - c#

I have a class in my model in MVC:
public class NewModel
{
public bool AllComplexes { get; set; }
public int UserID { get; set; }
public int? RoleID { get; set; }
public int ComplexID { get; set; }
[Required(ErrorMessage = "Please enter a user name."), StringLength(50)]
public string Username { get; set; }
[Required(ErrorMessage = "Please enter Password"), StringLength(100, ErrorMessage = "Password cannot be longer than 100 characters")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Passwords do not match")]
[Required(ErrorMessage = "Please confirm Password")]
public string RetypePassword { get; set; }
[RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )]
[Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)]
public string Email { get; set; }
public List<NEWCategoryModel> Categories { get; set; }
//public List<NEWPrivilegeModel> userPrivList { get; set; }
public List<DropDownItem> ComplexList { get; set; }
public List<DropDownItem> RoleList { get; set; }
public string NewRole { get; set; }
public NewModel()
{
}
}
The Email address entered is stored in :
public string Email { get; set; }
I need to compare that Email address to all the email addresses stored in the database using Data Annotation. I assume I will need a Custom Data Annotation? But I have no idea how to do it.
This is an example of the query to get al the email addresses from the database:
db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail);

public class NewModel
{
[EmailValidation(ErrorMessage = "The Email Address already exists")]
[RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )]
[Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)]
public string Email { get; set; }
{
public class EmailValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropmetEntities db = new PropmetEntities();
if (value != null)
{
var valueAsString = value.ToString();
IEnumerable<string> email = db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail);
if (email.Contains(valueAsString))
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}

This can help you to create custom validation. Then, to check user is already exist in database by email, try:
bool exist = db.UserTable.Any(e => e.Email.ToLower() == emailValue.ToLower());

In this post you'll find a solution leveraging FluentValidation, which implements a custom DataAnnotation.
Your Unique Email Validation would look something along these lines:
[Validator(typeof(NewModelValidator))]
class NewModel
{
//...Model implementation omitted
}
public class NewModelValidator : AbstractValidator<NewModel>
{
public NewModelValidator()
{
RuleFor(x => x.Email).Must(IsUnieuqEmail).WithMessage("Email already exists");
}
private bool IsUniqueEmail(string mail)
{
var _db = new DataContext();
if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;
return false;
}
}

Related

How do I make a relationship between my Aspnetusers table and a custom table?

I have extended my Aspnetusers table to include FirstName, MiddleName, LastName, StudentID.
I want a simple registation page where in the admin will create student accounts. The student accounts then should
be able to add their own personal contact details.
Now, I created a custom table named "ContactDetails" containing the ff:
public class Contact
{
[Key]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Display(Name = "Contact Number")]
public string StudentContactNumber { get; set; }
[Display(Name = "Mother First Name")]
public string MotherFirstName { get; set; }
[Display(Name = "Mother Middle Name")]
public string MotherMiddleName { get; set; }
[Display(Name = "Mother Last Name")]
public string MotherLastName { get; set; }
[Display(Name = "Mother Contact Number")]
public string MotherContactNumber { get; set; }
[Display(Name = "Father First Name")]
public string FatherFirstName { get; set; }
[Display(Name = "Father Middle Name")]
public string FatherMiddleName { get; set; }
[Display(Name = "Father Last Name")]
public string FatherLastName { get; set; }
[Display(Name = "Father Contact Number")]
public string FatherContactNumber { get; set; }
[Display(Name = "Emergency First Name")]
public string EmergencyFirstName { get; set; }
[Display(Name = "Emergency Middle Name")]
public string EmergencyMiddleName { get; set; }
[Display(Name = "Emergency Last Name")]
public string EmergencyLastName { get; set; }
[Display(Name = "Emergency Contact Number")]
public string EmergencyContactNumber { get; set; }
public virtual ApplicationUser User { get; set; }
}
IdentityModels class:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string StudentID { get; set; }
public string College { get; set; }
public virtual System.Collections.Generic.ICollection<Contact> ContactInfo { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
How do I put my user(Aspnetusers.Id) in ContactDetails (User_Id) table when the student is registered?
How do I make a relationship between them?
My AdminController:
// GET: /Admin/Edit/Create
[Authorize(Roles = "Administrator")]
#region public ActionResult Create()
public ActionResult Create()
{
ExpandedUserDTO objExpandedUserDTO = new ExpandedUserDTO();
ViewBag.Roles = GetAllRolesAsSelectList();
return View(objExpandedUserDTO);
}
#endregion
// PUT: /Admin/Create
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
#region
public ActionResult Create(ExpandedUserDTO paramExpandedUserDTO)
{
try
{
if (paramExpandedUserDTO == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Email = paramExpandedUserDTO.Email.Trim();
var UserName = paramExpandedUserDTO.Email.Trim();
var Password = paramExpandedUserDTO.Password.Trim();
//
var FirstName = paramExpandedUserDTO.FirstName.Trim();
var MiddleName = paramExpandedUserDTO.MiddleName.Trim();
var LastName = paramExpandedUserDTO.LastName.Trim();
var StudentID = paramExpandedUserDTO.StudentID.Trim();
var College = paramExpandedUserDTO.College.Trim();
// UserName is LowerCase of the Email
UserName = Email.ToLower();
// Create user
var objNewAdminUser = new ApplicationUser { UserName = UserName, Email = Email, FirstName = FirstName, MiddleName = MiddleName, LastName = LastName, StudentID = StudentID, College = College };
var AdminUserCreateResult = UserManager.Create(objNewAdminUser, Password);
if (AdminUserCreateResult.Succeeded == true)
{
string strNewRole = Convert.ToString(Request.Form["Roles"]);
if (strNewRole != "0")
{
// Put user in role
UserManager.AddToRole(objNewAdminUser.Id, strNewRole);
}
return Redirect("~/Admin");
}
else
{
ViewBag.Roles = GetAllRolesAsSelectList();
ModelState.AddModelError(string.Empty, "Error: User "+Email+ " already exists!");
//"Error: Failed to create the user. Check password requirements.");
return View(paramExpandedUserDTO);
}
}
catch (Exception ex)
{
ViewBag.Roles = GetAllRolesAsSelectList();
//ModelState.AddModelError(string.Empty, "Error: " + ex);
return View("Create");
}
}
#endregion
Im not sure how do I proceed? Thanks in advance.
In Contact class you should have these:
public int UserId { get; set; }
public virtual ApplicationUser User { get; set; }
In ApplicationUser class you should have these:
public int ContactId { get; set; }
public virtual Contact Contact { get; set; }

Pass a user to a ViewModel

OK, a little stuck here.
VIEWMODEL
public class UserProfileEdit
{
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
public string FirstName { get; set; }
public string TwitterHandle{ get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
// etc etc
}
CONTROLLER
public ActionResult YourProfile()
{
string username = User.Identity.Name;
ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));
// Construct the viewmodel
UserProfileEdit model = new UserProfileEdit();
model.ApplicationUser = user;
return View(model);
}
And on the View I have #model MySite.Models.UserProfileEdit at the top.
How can I pass the user to the ViewModel? I know I can do it line by line
model.Email = user.Email;
for example, but it should be simpler?
You can do it line by line, or you can use AutoMapper. Give it a try http://automapper.org/
This is very useful specially when you have the same kind of object mappings repeated in your code.
You have several options to do what you want to do.
You can use a tool, like AutoMapper.
Or you can pass data by a constructor :
public class UserProfileEdit
{
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
public string FirstName { get; set; }
public string TwitterHandle{ get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
// etc etc
public UserProfileEdit() {}
public UserProfileEdit(ApplicationUser user) {
this.ApplicationUser = user;
this.Email = user.Email;
// ...
}
}
public ActionResult YourProfile()
{
string username = User.Identity.Name;
ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));
return View(new UserProfileEdit(user));
}
Or using a method to init your view model's data :
public class UserProfileEdit
{
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
public string FirstName { get; set; }
public string TwitterHandle{ get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
// etc etc
public void Init(ApplicationUser user) {
this.ApplicationUser = user;
this.Email = user.Email;
// do what you want to do
}
}
public ActionResult YourProfile()
{
string username = User.Identity.Name;
ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));
UserProfileEdit vm = new UserProfileEdit();
vm.Init(user);
return View(vm);
}

How to not make information save to database-ASP.NET MVC

How do I validate & potentially charge Credit Card details server side (in the Create function below) without saving these details to a database.
Create ActionResult
public ActionResult Create()
{
var model = new Payment();
model.ValidFrom = DateTime.Now;
return View(new Payment());
}
// POST: Payments/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,CardName,CardNumber,ValidFrom,Expires,CardSecurityCode,EmailAddress,ConfrimEmailAddress,Address,City,Country,PostCode")] PaymentViewModel paymentViewModel ,Payment payment)
{
if (ModelState.IsValid)
{
payment = new Payment();
payment.EmailAddress = paymentViewModel.EmailAddress;
payment.ConfrimEmailAddress = paymentViewModel.ConfirmEmailAddress;
payment.Address = paymentViewModel.Address;
payment.City = paymentViewModel.City;
payment.Country = paymentViewModel.Country;
payment.PostCode = paymentViewModel.PostCode;
db.Payments.Add(payment);
db.SaveChanges();
return RedirectToAction("Details", "Payments", new { id = payment.ID });
}
return View(paymentViewModel);
}
Model
public class Payment
{
public int ID { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string CardName { get; set; }
// ------------------------------Visa Card ---------------------------------------------//
[RegularExpression(#"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$", ErrorMessage = "Invalid Card Number You Paki")]
public string CardNumber { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime ValidFrom { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime Expires { get; set; }
public string CardSecurityCode { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfrimEmailAddress { get; set; }
[RegularExpression(#"([a-zA-Z0-9\s]+)", ErrorMessage = "Invalid Address")]
public string Address { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string City { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string Country { get; set; }
[RegularExpression(#"\b\d{5}(?:-\d{4})?\b+", ErrorMessage = "Invalid postcode")]
public string PostCode { get; set; }
}
public class PaymentDBContext : DbContext //controls information in database
{
public DbSet<Payment> Payments { get; set; } //creates a donation database
public System.Data.Entity.DbSet<CharitySite.Models.Charity> Charities { get; set; }
}
I need to be able to retrive the Credit Card numbers without storing them in the database. Our original idea was to validate Credit Card Details client side using Javascript but project requirements dictate that server sided validation is performed.
If you only need to save a part of the information, and use the rest only for validation purposes (eg, validate the number of credit card), then you must use a ViewModel that contains all the information requested on the form, and extract from the ViewModel only the information you need save:
ViewModel:
public class PaymentViewModel
{
public int ID { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string CardName { get; set; }
// ------------------------------Visa Card ---------------------------------------------//
[RegularExpression(#"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$", ErrorMessage = "Invalid Card Number You Paki")]
public string CardNumber { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime ValidFrom { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime Expires { get; set; }
public string CardSecurityCode { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfrimEmailAddress { get; set; }
[RegularExpression(#"([a-zA-Z0-9\s]+)", ErrorMessage = "Invalid Address")]
public string Address { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string City { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string Country { get; set; }
[RegularExpression(#"\b\d{5}(?:-\d{4})?\b+", ErrorMessage = "Invalid postcode")]
public string PostCode { get; set; }
}
Model (only containing fields to save):
public class Payment
{
public int ID { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfrimEmailAddress { get; set; }
[RegularExpression(#"([a-zA-Z0-9\s]+)", ErrorMessage = "Invalid Address")]
public string Address { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string City { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string Country { get; set; }
[RegularExpression(#"\b\d{5}(?:-\d{4})?\b+", ErrorMessage = "Invalid postcode")]
public string PostCode { get; set; }
}
public class PaymentDBContext : DbContext //controls information in database
{
public DbSet<Payment> Payments { get; set; } //creates a donation database
public System.Data.Entity.DbSet<CharitySite.Models.Charity> Charities { get; set; }
}
Create Action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PaymentViewModel paymentViewModel)
{
if (ModelState.IsValid)
{
// Some validation on credit card before save payment...
// Save payment
payment = new Payment();
payment.EmailAddress = paymentViewModel.EmailAddress;
payment.ConfirmEmailAddress = paymentViewModel.ConfirmEmailAddress;
payment.Address = paymentViewModel.Address;
payment.City = paymentViewModel.City;
payment.Country = paymentViewModel.Country
payment.PostCode = paymentViewModel.PostCode;
db.Payments.Add(payment);
db.SaveChanges();
return RedirectToAction("Details", "Payments", new { id = payment.ID });
}
return View(paymentViewModel);
}
And change the Model used in your View:
#model [yourNameSpace].paymentViewModel
As far as I am aware there is no legislation actively prohibiting you from storing Credit Card details. Though certain aspects of your implementation may fail PCI compliance. For example, you may store the credit card number and expiry date but this must be in an encrypted form, you may NEVER store the CCV in any form.
Either way it isn't really recommended that you take on the burden of storing CC numbers, unless you have considerable experience and compliance budget. The only advantage I can really see to this is the consumer convenience of not having to repeatedly enter details. Most payment processors should allow you pass details to them for charging. If you choose this approach you may want to look into usage of the SecureString class which will allow you to dispose of details as soon as you have transmitted them to the processor.

NullReferenceException Error in ASP.NET MVC [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have NullReferenceException error in forgotten password section. Where is my mistake and how can I fix it? Here are my codes:
my controller :
public ActionResult ForGotPasswordSent(ForGotModel forgetModel)
{
User user = _userService.GetUserByEmail(forgetModel.Email);
if (user.IsActive)
{
var objEmail = new EmailHelper();
Message msg = new Message();
msg.SuccessMessage = "You have sent the mail,Please verify that";
msg.IsSuccess = true;
string strBody = "Thanks for using the forgot password function.You need to set new password to your account, please click here to proceed";
bool result = objEmail.SendMail("noreply#xx.com", "xxtest#gmail.com", "", "Activate Your Account", strBody, true);
if (result)
return View("Activation", msg);
else
return View("Activation");
}
else
{
this.ModelState.AddModelError("", "You have to activate your account");
return View("Activation");
}
}
my User class:
public class User : IPrincipal
{
public int Id { get; set; }
[Required(ErrorMessage = "Kullanıcı adı girilmesi zorunludur.")]
[Display(Name = "Kullanıcı Adı")]
public string Username { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Password Required")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public bool IsActive { get; set; }
public bool IsAdmin { get; set; }
public bool IsDeleted { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
my ForgotModel
public class ForGotModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
_userService.GetUserByEmail method:
public User GetUserByEmail(string email)
{
var user = _userRepository.Get(x => x.Email == email);
return user;
}
You probably will want to add a null check to user before checking the IsActive property. Try this:
if (user != null && user.IsActive)
GetUserByEmail might return null, when no user is found. Verify that your User object is not null before checking for user.IsActive.

MVC 5 GetUserId() returns null

I have created a custom User class implementing IUser.
When I register everything completes fine, the tables are created (if they don't exist) and all looks ok, but, as the subject states, I cannot get User.GetUserId() to work.
It always returns null which is really annoying.
Here is my User class:
public class User : IUser
{
public User()
{
this.LastLoginDate = DateTime.UtcNow;
this.DateCreated = DateTime.UtcNow;
}
public User(string userName)
{
this.Id = Guid.NewGuid().ToString();
this.UserName = userName;
this.CreatedBy = this.Id;
this.LastLoginDate = DateTime.UtcNow;
this.DateCreated = DateTime.UtcNow;
this.IsApproved = true;
}
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredUserName")]
public string UserName { get; set; }
public string Id { get; set; }
[Required] public string CompanyId { get; set; }
[Required] public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public DateTime LastLoginDate { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredTitle")]
public string Title { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredFirstName")]
public string Forename { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredLastName")]
public string Surname { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredEmail")]
public string Email { get; set; }
public string JobTitle { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public string Photo { get; set; }
public string LinkedIn { get; set; }
public string Twitter { get; set; }
public string Facebook { get; set; }
public string Google { get; set; }
public string Bio { get; set; }
public string CompanyName { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredCredentialId")]
public string CredentialId { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredSecurityCode")]
public bool IsLockedOut { get; set; }
public bool IsApproved { get; set; }
[Display(Name = "Can only edit own assets")]
public bool CanEditOwn { get; set; }
[Display(Name = "Can edit assets")]
public bool CanEdit { get; set; }
[Display(Name = "Can download assets")]
public bool CanDownload { get; set; }
[Display(Name = "Require approval to upload assets")]
public bool RequiresApproval { get; set; }
[Display(Name = "Can approve assets")]
public bool CanApprove { get; set; }
[Display(Name = "Can synchronise assets")]
public bool CanSync { get; set; }
public bool AgreedTerms { get; set; }
public bool Deleted { get; set; }
}
public class UserContext : IdentityStoreContext
{
public UserContext(DbContext db)
: base(db)
{
this.Users = new UserStore<User>(this.DbContext);
}
}
public class UserDbContext : IdentityDbContext<User, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
Here is my Register function:
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Create a profile, password, and link the local login before signing in the user
var companyId = Guid.NewGuid().ToString();
var user = new Skipstone.Models.User(model.UserName)
{
CompanyId = companyId,
Title = model.Title,
Forename = model.Forename,
Surname = model.Surname,
Email = model.Email,
CompanyName = model.CompanyName,
CredentialId = model.CredentialId
};
if (await IdentityStore.CreateLocalUser(user, model.Password))
{
// Create our company
var company = new Company()
{
Id = companyId,
CreatedBy = user.Id,
ModifiedBy = user.Id,
Name = model.CompanyName
};
using (var service = new CompanyService())
{
service.Save(company);
}
await AuthenticationManager.SignIn(HttpContext, user.Id, isPersistent: false);
var test = User.Identity.IsAuthenticated; // returns true
var u = User.Identity.GetUserId(); // returns null
return RedirectToAction("Setup", new { id = companyId });
}
else
{
ModelState.AddModelError("", "Failed to register user name: " + model.UserName);
}
}
catch (IdentityException e)
{
ModelState.AddModelError("", e.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
var test returns true, so it knows the user is now logged in.
var u is null, so User.Identity.GetUserId() is not working as it should.
Does anyone have any idea why?
I can post more code on request :)
Update 1
By creating a fresh project and testing with defaults, I have found that called User.Identity returns null when in the Register method.
But in the fresh project, calling it anywhere else returns the right information, but in my project I get null for everything.
Update 2
It is definately related to the custom User class.
I created one on my fresh project and the same thing happens.
So, something is wrong :) now I just have to figure out what!?!
I assume somewhere in your project there is a row of database connection initialization, something like this:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true)
So, make sure that you use "Id" instead of "UserId" in this line

Categories