2015-04-22 22 views
1

我有以下部分視圖與Html.FormBegin助手方法;MVC部分視圖回傳調用錯誤的方法

@if (Session["UserSpecific"]!=null) //(Request.IsAuthenticated) 
{ 
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) 
    { 
    @Html.AntiForgeryToken() 
      @* @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })*@ 

      <input type="button" class="menu-button nav navbar-nav navbar-right" data-target=".customer-list" data-toggle="collapse" /> 

      <div class="customer-list-container"> 
       <div class="customer-list collapse"> 
        <ul> 
         @{ 
          string[] array = { "Steel Company", "Recycling Company", "Other Company", "Random Name Here" }; 
         } 

         @foreach (string name in array) 
         { 
          <li>@Html.ActionLink(name, "", "", routeValues: null, htmlAttributes: new { @class = "customer-link" })</li><hr/> 
         } 

         <li><input type="submit" /></li> 
        </ul> 
        <div class="col-xs-6">@Html.ActionLink("Settings", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })</div><div class="col-xs-6"><!--<input type="submit" value="Log Off"/>-><!--<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></div><div class="clearfix">--></div> 
       </div> 
      </div> 
    } 
} 

的問題是,每當我點擊的不是註銷提交按鈕,它通過登錄方法再次運行,並修改網址爲:

Account/Login?ReturnUrl=%2FAccount%2FLogOff 

我不得到爲什麼它再次通過LogIn方法運行,因爲Html.BeginForm方法指定它將使用Account控制器中的LogOff方法。

登錄方法被調用:

 // GET: /Account/Login 
    [AllowAnonymous] 
    public ActionResult Login(string returnUrl) 
    { 
     ViewBag.ReturnUrl = returnUrl; 
     return View(); 
    } 

註銷方法應該被稱爲:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult LogOff() 
    { 
     //AuthenticationManager.SignOut(); 
     Session.Remove("UserSpecific"); 
     Session["UserSpecific"] = null; 
     return RedirectToAction("Index", "Home"); 
    } 
+0

你的'HomeController'或者'HomeController'上的'Index'操作方法是否具有'[AllowAnonymous]'屬性? – BG100

+0

Index action方法已經標記爲AllowAnonymous,但是當我在代碼中放置一箇中斷時,而不是LogOff操作方法(應該根據Html.BeginForm方法調用)時,Login操作方法仍然被打中。 –

+0

這部分被渲染在主視圖中的'

'標籤內? (嵌套表單無效並且不受支持) –

回答

0

它看起來像Index操作方法您HomeController未標明[AllowAnonymous]屬性,這意味着當瀏覽器在註銷後嘗試訪問它時,它會重新定向到登錄頁面,因爲您嘗試訪問僅供經過驗證的用戶訪問的頁面。

嘗試增加[AllowAnonymous]

public class HomeController : Controller { 

    [AllowAnonymous] // <-- add this 
    public ActionResult Index() { 
     return View(); 
    } 

    // other stuff 
} 
+0

這並沒有幫助,但在我放置斷點時,AccountController.cs中的LogOff()方法仍未被命中,但仍標記爲[AllowAnonymous]的登錄仍處於打中狀態。 –

+0

是否因爲你的表單被配置爲'FormMethod.Post',但你已經在你的'LogOff'操作方法中註釋掉了'[HttpPost]'屬性? – BG100

+0

哎呦,讓我解決這個問題。我發佈後,我發佈了它,並將其更改爲我的代碼,但忘記在這裏更改它 –

0

我只是意識到一些有趣的事情,我面臨着同樣的問題,我的MVC面積要求在賬戶控制器索引方法,而不是調用註銷方法。 我意識到問題是在應用程序的管理區域中完成了有缺陷的路由。 嘗試測試,看看你是否能夠糾正它。

相關問題