簡體   English   中英

將asp.net從WebForms遷移到MVC時形成身份驗證問題

[英]Forms authentication problems when migrating asp.net from WebForms to MVC

我正在逐步將我的項目從asp.net Web表單升級到MVC4。 在第一步中,我更改了登錄頁面和其他幾頁。 我正在使用表單身份驗證,我自己的邏輯(沒有成員資格) - 我檢查數據庫表的用戶名/密碼。 如果沒有問題,則將用戶重定向到其目的地。 我的登錄代碼是:

Web.config文件:

<authentication mode="Forms">
    <forms loginUrl="~/LogIn" name=".ASPXFORMSAUTH" timeout="150" />
</authentication>
<authorization>
    <deny users="?" /> 
</authorization>

登錄控制器:

[AllowAnonymous]
[HttpPost]
public ActionResult AjaxLogin(FormCollection postedFormData)
{
    try
    {
        string userName = postedFormData["Login_UserName"];
        string password = postedFormData["Login_Password"];
        UserEntity userEntity = new UserEntity(Utilities.AuthenticateUser(userName, password, 1));

        Session["UserEntity"] = userEntity;

        FormsAuthentication.SetAuthCookie(userEntity.Key.Id.ToString(), false);

        return Json(new { redirectToUrl = "./AccountSelection", error = "false", lan = Thread.CurrentThread.CurrentUICulture.ToString() });
    }
    catch (Exception ex)
    {
         return Json(new { redirectToUrl = "", error = ExceptionHandler.HandleException(ex), lan = Thread.CurrentThread.CurrentUICulture.ToString() });
    }
}

當我嘗試登錄時,我得到http 302並重定向回登錄。 如果我刪除web.config上的“授權”部分它將正常工作,但現在我有兩個問題:

  1. 我必須在每個控制器上放置[authorize]屬性
  2. 我的webforms不會在表單身份驗證中(可以直接訪問而無需登錄!!)

我究竟做錯了什么?

如果您在web.config中定義授權,則不需要AllowAnonymousAttribute。

話雖如此,您似乎沒有將AjaxLogin添加到授權列表中。 這是必要的,因為否則會阻止Ajax請求。 你需要〜/ Login和〜/ Account / AjaxLogin路徑。 您可能還需要〜/帳戶/登錄路徑,但我不確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM