I built a query to find a user by the username. When I run the program I get:
InvalidOperationException: Sequence contains more than one element
I checked the test database, and there's with only 4 users and no double names. Where can the exception come from? Here is the query:
public void setUser(String userName)
{
AzaraUser = DatabaseConnection.DataContext.GetTable<AzaraUser>()
.SingleOrDefault(a => a.ProgramUserName == userName || a.UserName == userName);
}
With the tips below I tried debugging and found that the method becomes an empty string. So in this case it's normal that I get several responses because the ProgramUserName is only in a few rows not null because it is for user who log in with an active directory account.
But why do I get this empty string? Could it be that the WebSecurity is also empty on that moment? At which point will it get the information about the current user?
Here is my log in method:
[HttpPost]
public ActionResult Login(FormCollection logInForm)
{
// try the default membership auth
if (Membership.ValidateUser(logInForm["name"], logInForm["password"]))
{
FormsAuthentication.SetAuthCookie(logInForm["name"], false);
user.setUser(WebSecurity.CurrentUserName);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
{
Response.Redirect("~/home/index");
}
else
{
Response.Redirect(returnUrl);
}
}
else
{
ModelState.AddModelError("", "Login failed");
}
// try to auth user via AD
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
if (pc.ValidateCredentials(logInForm["name"], logInForm["password"]))
{
FormsAuthentication.SetAuthCookie(logInForm["name"], false);
user.setUser(WebSecurity.CurrentUserName);
return RedirectToAction("Index", "Home");
}
}
return View("LogOn");
}