2016-06-27 78 views
0

我想這樣做,如果用戶登錄在數據庫中持有密碼「tja」將他發送到一個頁面,否則另一個,但不能讓它工作。在mvc需要幫助

任何人都可以請幫我使用正確的代碼嗎?

//This is the code I have now. 

public string mypassword = "tja"; 

// GET: SmsBuys 
public ActionResult Index() 
{ 
     var getuser = User.Identity.GetUserId(); 
     var getpassword = db.SmsBuys.Where(x => x.code == mypassword); 

     if (getpassword == getuser) //This is wrong I know 
     { 
      return RedirectToAction("Index", "Buys"); 
     } 
     else 
     { 
      return View(db.SmsBuys.ToList().Where(x => x.UserId == User.Identity.GetUserId())); 
     } 
} 

回答

0

處理密碼輔助

當前用戶的密碼真的只打算時,他們張貼到服務器進行訪問。

因此,您可能需要在實際的POST事件中處理它,在該事件中您的用戶將其適當的登錄憑據發佈到服務器以便在應用程序中進行身份驗證。

比方說,你有一個看起來像這樣爲用戶登錄一個非常基本的形式:

<form action='@Url.Action("SignIn","Account")' method='post'> 
    <input name='username' placeholder='Username' /> 
    <input name='password' type='password' placeholder='Password' /> 
    <input type='submit' value='Log In' /> 
</form> 

當發佈,這將尋找您的賬戶控制器內的簽到行爲看起來像以下,這是在那裏你會處理這樣的邏輯:

[HttpPost] 
public ActionResult SignIn(string username, string password) 
{ 
     // Compare your password 
     if(password == yourSpecialPassword) 
     { 
      return RedirectToAction("Index", "Buys"); 
     } 

     // If you are still around, authenticate the user here 
} 

用戶的密碼將沿着password變量,然後你就可以用它來比較對你的數據庫值來確定要採取的行動最好的辦法通過。

從數據庫訪問

此外,如果你正在閱讀您的密碼,以覈對從數據庫中,你可能會想使用FirstOrDefault()方法來拉動,而不是Where()單,而這樣做返回它們的集合:

var getpassword = db.SmsBuys.FirstOrDefault(x => x.code == mypassword); 
// If a password was found, check against the posted value 
if(password == getpassword) 
{ 
     return RedirectToAction("Index", "Buys"); 
} 
+0

我已經修復了它,我用了一個餅乾:) – Daniel

+0

您是否將用戶的密碼存儲在cookie中?似乎並不實際可以堅持像密碼那樣敏感的東西,只能用於處理重定向。我強烈建議在POST事件中提交這個內容,因爲它似乎對我更有意義,但是您的里程數/使用情況可能會有所不同。 –

+0

否否不將用戶的密碼存儲在cookie中。只需使用一個cookie,以便我可以寫入,如果(smscookie!= null)轉到本網站,否則轉到另一個☺ – Daniel