2013-11-23 67 views
1

標題說明了一切,我希望它這樣,如果用戶試圖瀏覽到的任何網頁或網站訪問任何被重定向到一個登錄頁面,這只是如果沒有登錄HES。如何將用戶重定向到網站中的特定頁面(如果他沒有登錄)?

這是我的簡單登錄代碼:

public ActionResult login(MvcMobile.Models.Users x) 
    { 
     var user = db.Users.FirstOrDefault(u => u.username == x.username && u.password == x.password); 


    if (user == null) 
     ModelState.AddModelError("","username or password is wrong."); 

    else 
    { 
     FormsAuthentication.SetAuthCookie(user.username, false); 
     Response.Redirect("/"); 
    } 
    return View(user); 
} 

我試圖將此代碼放在主要的佈局,但我得到了一個無限重定向循環:P

@if (User.Identity.IsAuthenticated) 
        { 
      <p> Hi @User.Identity.Name</p> 
        } 
        else 
         { 

         Response.Redirect("~/home/login"); 
        } 

什麼想法?

+0

我編輯了您的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

7

改爲使用[Authorize]屬性裝飾您的控制器/操作。或者,如果你希望這適用於所有控制器添加它作爲一個全球性的動作過濾器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new AuthorizeAttribute()); 
} 

當然通過與[AllowAnonymous]屬性裝飾它這樣做,你可能要排除驗證您的AccountController作者:

然後在你的web.config中,設置loginUrl頁面表單認證標籤的指向登錄頁面,所有匿名用戶將被重定向到:

<authentication mode="Forms"> 
    <forms loginUrl="~/home/login" /> 
</authentication> 
+0

謝謝,但即時通訊仍然被重定向到默認的登錄網址,並且每當我運行應用程序時,我都會收到「錯誤提示」無法識別的配置節身份驗證。 , 任何想法 ? – user2962142

+0

你把這部分放在哪裏?你把它放在''節點內嗎?請閱讀下面的文章,以更好地瞭解Forms Authentication如何在ASP.NET中工作:http://msdn.microsoft.com/en-us/library/ff647070.aspx –

+0

我剛把它移到那裏,我得到這個錯誤: 「在應用程序級別之外使用註冊爲allowDefinition ='MachineToApplication'的部分是錯誤的,該錯誤可能是由於虛擬目錄沒有被配置爲IIS中的應用程序。」 – user2962142

1

除了Darin Dimitrov's answer ,您還應該在Web.config文件中配置LoginUrl屬性,例如:

<authentication mode="Forms"> 
    <forms loginUrl="member_login.aspx" 
    defaultUrl="index.aspx" /> 
</authentication> 
+1

這與Darin的答案有何不同? –

+1

事實上Darin Dimitrov後來編輯並添加了配置部分:-) – afzalulh

相關問題