2014-05-05 69 views
1

我有這個網站在我的asp.net MVC 4應用:asp.net MVC 4註銷功能不能正常工作

@if (User.Identity.IsAuthenticated) 
       <li class="login-link">  { 
    @Html.ActionLink(User.Identity.Name, "LogOff", "Account") 
</li> 
} 

這個控制器動作

//[HttpPost] 
//[ValidateAntiForgeryToken] 
public ActionResult LogOff() 
{ 
    WebSecurity.Logout(); 

    return RedirectToAction("Index", "Home"); 
} 

但是當我點擊日誌out鏈接,用戶不會註銷。

請建議如何解決它

+0

能否將Html.actionlink()生成的鏈接粘貼到瀏覽器中? –

回答

0

我找不到任何錯誤的代碼。 但是試試這個,讓我知道它是否適合你:

CSHTML:

@Html.ActionLink("Log Off", "LogOff", "LogOn", null, new { @class = "actnclass" }) 

控制器:

public ActionResult LogOff() 
{ 
    Request.Cookies.Remove("UserId"); 
    FormsAuthentication.SignOut(); 
    return RedirectToAction("LogOn", "LogOn"); 
} 
+0

如果您找不到有人發佈的代碼有任何問題,請不要只需複製粘貼自己的代碼即可。另一個答案指出了代碼的一些具體問題。 –

0

你的剃鬚刀的代碼看起來不錯。即使是像下面這樣一個基本的HTML代碼註銷應該做

<a href="@Href("~/Account/LogOff")">Logout</a> 

請您註銷等動作斷點在您的賬戶控制器和看到發生了什麼。您好像使用WebSecurity.Logout();註銷,然後將用戶重定向到Home/Index頁面。

另外想知道通過看看你推斷該用戶沒有註銷。

2

在上面的代碼示例中,你寫道:根據您的@if (User.Identity.IsAuthenticated)聲明如何解決,這可能導致一些靠不住的代碼正在爲瀏覽器呈現

@if (User.Identity.IsAuthenticated) 
       <li class="login-link">  { 
    @Html.ActionLink(User.Identity.Name, "LogOff", "Account") 
</li> 
} 

以下Razor代碼是否更加正確地反映您的意圖?

@if (User.Identity.IsAuthenticated) 
{ 
    <li class="login-link"> 
     @Html.ActionLink(User.Identity.Name, "LogOff", "Account") 
    </li> 
} 
0

你的代碼沒有問題。重點是帳戶中的操作註銷是HttpPost方法,因此它只會接受表單提交。

你必須3種方式來實現註銷功能

  1. 變更註銷等方法HTTPGET代替HttpPost的賬戶控制器
  2. 添加HTTPGET過載爲它取一個參數離開HttpPost方法賬戶控制器

    [HttpGet] 
    public ActionResult LogOff(string token) { 
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 
        return RedirectToAction("Index", "Home"); 
    } 
    
    // Already Exists 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult LogOff() { 
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 
        return RedirectToAction("Index", "Home"); 
    } 
    
  3. 使用JavaScript來提交註銷形式

    @using Microsoft.AspNet.Identity 
    @if (Request.IsAuthenticated) 
    { 
        using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) 
        { 
         @Html.AntiForgeryToken() 
         // ... 
         <a href="javascript:document.getElementById('logoutForm').submit()">LogOff</a> 
        } 
    }