【问题标题】:Forms authentication problems when migrating asp.net from WebForms to MVC将 asp.net 从 WebForms 迁移到 MVC 时的表单身份验证问题
【发布时间】:2012-05-22 13:55:17
【问题描述】:

我正在逐步将我的项目从 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. 我的网络表单不会在表单内进行身份验证(无需登录即可直接访问!!)

我做错了什么?

【问题讨论】:

    标签: c# jquery asp.net asp.net-mvc forms-authentication


    【解决方案1】:

    如果您在 web.config 中定义您的授权,则不需要 AllowAnonymousAttribute。

    话虽如此,您似乎并未将 AjaxLogin 添加到您的授权列表中。这是必要的,因为否则 Ajax 请求将被阻止。您需要 ~/Login 和 ~/Account/AjaxLogin 路径。您可能还需要一个 ~/Account/Login 路径,但我不确定。

    【讨论】:

    • 感谢您的帮助。我尝试将“~/Secure/AjaxLogin”添加到 web.config,但没有帮助。 (我给了控制器的溃败路径):&lt;location path="~/Login"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; &lt;location path="~/Secure/AjaxLogin"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt;
    • @Yaniv - 您是否将控制器名称更改为 SecureController?
    • 是的,我做到了 - 控制器被命名为 -“SecureController”。是这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2017-08-24
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    相关资源
    最近更新 更多