2012-11-05 38 views
4

下面是我嘗試的一些代碼。這是行不通的; 「登錄」後,用戶不會重定向到主頁/索引頁面,但登錄頁面只是重新加載。如何使用ASP.NET MVC4登錄?

Web.config文件:

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/Login" /> 
</authentication> 

... 

<defaultDocument> 
    <files> 
    <add value="~/Account/Login"/> 
    </files> 
</defaultDocument> 

控制器/ AccountController.cs:

public class AccountController : Controller 
{ 
    // 
    // GET: /Account/Login 
    public ActionResult Login() 
    { 
     return View(); 
    } 
} 

查看/帳號/的Login.aspx:

<asp:Login ID="login" runat="server" DestinationPageUrl="~/Views/Home/Index.aspx"> 
    ... 
</asp:Login> 
+0

你的登錄方法是空的,所以沒有人會得到驗證...?對於最簡單的表單驗證[msdn](http://msdn.microsoft.com/de-de/library/system.web.security.formsauthentication.authenticate.aspx) - 您需要登錄操作中的Login_OnClick部分。 – metadings

回答

11

?如果沒有,我建議你創建一個新的ASP.NET MVC項目與互聯網模板,打開帳戶控制器,看看和方法。

正如@ USER1說得好,你可以做到這一點的方法之一是使用

FormsAuthentication.SetAuthCookie(username, true); 
return Redirect(returnurl); 

但正如你說,你正在使用ASP.NET MVC 4,您應該使用WebSecurity類。

例如:

WebSecurity.Login(model.UserName, model.Password); 
return RedirectToAction("Index", "Home"); 

大部分的工作是使用WebSecurity幫手以下方法和屬性來完成:

延伸閱讀:

2

我懷疑你是不是設置形成認證cookie,這就是重定向不起作用的原因。理想情況下,你的登錄方法,你會使用一些邏輯驗證用戶名和密碼,你感到滿意的用戶是合法的時候,你必須設置窗體身份驗證Cookie,然後將用戶重定向

FormsAuthentication.SetAuthCookie(username, true); 
return Redirect(returnurl); 

如果您不要設置身份驗證cookie,重定向將不起作用,因爲請求仍然會被視爲未經身份驗證的請求,並且用戶將被髮送回登錄頁面。你可以找到更多信息表格是否使用ASP.NET MVC 4的網絡模板在此登陸

http://msdn.microsoft.com/en-us/library/xdt4thhy%28v=vs.71%29.aspx