2017-06-22 98 views
1

我正在我的MVC項目的登錄頁面上工作。MVC登錄功能

我想用一個已經存在的名爲DEVE03的數據庫來構建它。在DEVE03數據庫中,我有一個名爲User的表。我在這裏跟着一個教程:http://www.c-sharpcorner.com/article/Asp-Net-mvc-5-integrating-existing-database-with-login-usin/它工作正常。但在教程中,他使用存儲過程,並使用表格。

除了一件以外,每一樣東西都可以使用。代碼的這一部分是什麼var loginInfo = this.databaseManager.User(model.LogonName, model.LogonPassword).ToList();用戶給我一個錯誤,說明非invocable成員Entities.User不能像方法一樣使用。

我已經看到相當多的人有同樣的問題,人們建議他們應該刪除大多數人解決問題的括號。但是,當我刪除它的作品,我可以登錄。但我可以登錄每個可能的登錄名和登錄密碼。當我登錄時,登錄帳戶是我的表中的第一個帳戶。

我已經連接到我的數據庫visual studio,並且我已經創建了一個名爲CMS的實體數據模型。

我希望你們能幫助我

帳戶控制:

using System; 
using System.Globalization; 
using System.Linq; 
using System.Security.Claims; 
using System.Threading.Tasks; 
using System.Web; 
using System.Web.Mvc; 
using Microsoft.AspNet.Identity; 
using Microsoft.AspNet.Identity.Owin; 
using Microsoft.Owin.Security; 
using System.Collections.Generic; 
using Microsoft.AspNet.Identity.EntityFramework; 
using CMS.Models; 
using CMS.Models.DatabaseModels; 

namespace CMS.Controllers 
{ 

public class AccountController : Controller 
{ 
    #region Private Properties  

    private Entities databaseManager = new Entities(); 
    #endregion 
    #region Default Constructor  

    private ApplicationSignInManager _signInManager; 
    private ApplicationUserManager _userManager; 

    public ApplicationSignInManager SignInManager 
    { 
     get 
     { 
      return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); 
     } 
     private set 
     { 
      _signInManager = value; 
     } 
    } 

    public ApplicationUserManager UserManager 
    { 
     get 
     { 
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
     } 
     private set 
     { 
      _userManager = value; 
     } 
    } 

    public AccountController() 
    { 
    } 
    #endregion 
    #region Login methods  
    [AllowAnonymous] 
    public ActionResult Login(string returnUrl) 
    { 
     try 
     { 
      // Verification.  
      if (this.Request.IsAuthenticated) 
      { 
       // Info.  
       return this.RedirectToLocal(returnUrl); 
      } 
     } 
     catch (Exception ex) 
     { 
      // Info  
      Console.Write(ex); 
     } 
     // Info.  
     return this.View(); 
    } 
    /// <summary> 
    /// POST: /Account/Login  
    /// </summary> 
    /// <param name="model">Model parameter</param> 
    /// <param name="returnUrl">Return URL parameter</param> 
    /// <returns>Return login view</returns> 
    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public ActionResult Login(LoginViewModel model, string returnUrl) 
    { 
     try 
     { 
      // Verification.  
      if (ModelState.IsValid) 
      { 
       // Initialization.  
       var loginInfo = this.databaseManager.MDFUser(model.LogonName, model.LogonPassword).ToList(); 
       // Verification.  
       if (loginInfo != null && loginInfo.Count() > 0) 
       { 
        // Initialization.  
        var logindetails = loginInfo.First(); 
        // Login In.  
        this.SignInUser(logindetails.LogonName, false); 
        // Info.  
        return this.RedirectToLocal(returnUrl); 
       } 
       else 
       { 
        // Setting.  
        ModelState.AddModelError(string.Empty, "Email or password is incorrect"); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      // Info  
      Console.Write(ex); 
     } 
     // If we got this far, something failed, redisplay form  
     return this.View(model); 
    } 
    #endregion 
    #region Log Out method.  
    /// <summary> 
    /// POST: /Account/LogOff  
    /// </summary> 
    /// <returns>Return log off action</returns> 

    public ActionResult LogOff() 
    { 
     try 
     { 
      // Setting.  
      var ctx = Request.GetOwinContext(); 
      var authenticationManager = ctx.Authentication; 
      // Sign Out.  
      AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 
     } 
     catch (Exception ex) 
     { 
      // Info  
      throw ex; 
     } 
     // Info.  
     return this.RedirectToAction("Login", "Account"); 
    } 
    #endregion 
    #region Helpers  
    #region Sign In method.  
    /// <summary> 
    /// Sign In User method.  
    /// </summary> 
    /// <param name="username">Username parameter.</param> 
    /// <param name="isPersistent">Is persistent parameter.</param> 
    private void SignInUser(string username, bool isPersistent) 
    { 
     // Initialization.  
     var claims = new List<Claim>(); 
     try 
     { 
      // Setting  
      claims.Add(new Claim(ClaimTypes.Name, username)); 
      var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); 
      var ctx = Request.GetOwinContext(); 
      var authenticationManager = ctx.Authentication; 
      // Sign In.  
      authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, claimIdenties); 
     } 
     catch (Exception ex) 
     { 
      // Info  
      throw ex; 
     } 
    } 
    #endregion 
    #region Redirect to local method.  
    /// <summary> 
    /// Redirect to local method.  
    /// </summary> 
    /// <param name="returnUrl">Return URL parameter.</param> 
    /// <returns>Return redirection action</returns> 
    private ActionResult RedirectToLocal(string returnUrl) 
    { 
     try 
     { 
      // Verification.  
      if (Url.IsLocalUrl(returnUrl)) 
      { 
       // Info.  
       return this.Redirect(returnUrl); 
      } 
     } 
     catch (Exception ex) 
     { 
      // Info  
      throw ex; 
     } 
     // Info.  
     return this.RedirectToAction("Index", "Home"); 
    } 
    #endregion 

    #region Helpers 
    // Used for XSRF protection when adding external logins 
    private const string XsrfKey = "XsrfId"; 

    private IAuthenticationManager AuthenticationManager 
    { 
     get 
     { 
      return HttpContext.GetOwinContext().Authentication; 
     } 
    } 

    private void AddErrors(IdentityResult result) 
    { 
     foreach (var error in result.Errors) 
     { 
      ModelState.AddModelError("", error); 
     } 
    } 

    internal class ChallengeResult : HttpUnauthorizedResult 
    { 
     public ChallengeResult(string provider, string redirectUri) 
      : this(provider, redirectUri, null) 
     { 
     } 

     public ChallengeResult(string provider, string redirectUri, string userId) 
     { 
      LoginProvider = provider; 
      RedirectUri = redirectUri; 
      UserId = userId; 
     } 

     public string LoginProvider { get; set; } 
     public string RedirectUri { get; set; } 
     public string UserId { get; set; } 

     public override void ExecuteResult(ControllerContext context) 
     { 
      var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; 
      if (UserId != null) 
      { 
       properties.Dictionary[XsrfKey] = UserId; 
      } 
      context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); 
     } 
    } 
    #endregion 
    #endregion 
} 

}

LoginViewModel:

public class LoginViewModel 
    { 
    [Required] 
    [Display(Name = "Email")] 
    [EmailAddress] 
    public string LogonName { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    public string LogonPassword { get; set; } 

    public bool RememberMe { get; set; } 
} 

和用戶表看起來這樣的:我用它來登錄例如

UserID LogonName   LogonPassword 
1   [email protected] Welcome123 
2   [email protected] Welcome1234 
3   [email protected] Welcome12345 

所以,無論電子郵件住址:[email protected]他會登錄到[email protected]

我希望你們能幫我解決我的問題。

讓我知道如果我錯過了你可能需要解決的任何代碼。

+0

是的我有,但是當我刪除括號並且用[email protected]登錄時,它使用帳戶[email protected]登錄我。所以沒有進行驗證。 – HJarry

+0

請分享databaseManager.MDFUser()方法代碼。 – Conqueror

+0

它在我上面顯示的accountcontroller我認爲 – HJarry

回答

1

因爲他使用S.Proc LoginByUsernamePassword它接受usernamepassword作爲參數(就像C#中的方法)。

在你的情況MDFUser是你的數據庫中的表,所以你不能這樣做。

當你刪除你實際上是說括號:

var loginInfo = this.databaseManager.MDFUser.ToList();

讓我一切的列表中MDFUser

您需要查詢的表像這樣(如果語法不是100%的話,請原諒我)。

var loginInfo = this.databaseManager.MDFUser.Where(n=>n.username == 
        model.username && n.password == model.password).ToList(); 
...other code... 
+0

我試過了,但它現在給我一個錯誤logininfo不存在於當前上下文 – HJarry

+0

不知道明白了。你剛剛救了我的生命我的朋友! – HJarry

+0

@HJarry沒有問題 - 我指出另外一件事(只是爲了防止你這樣做):不要將密碼作爲純文本存儲在數據庫中。 – scgough