【问题标题】:How to easily redirect if not authenticated in MVC 3?如果未在 MVC 3 中进行身份验证,如何轻松重定向?
【发布时间】:2011-07-21 02:02:06
【问题描述】:

我是 ASP.NET 的新手,我正在尝试找到一种方法来轻松地将未经身份验证的用户从站点上的任何页面重定向到登录页面。如果有其他选择,我宁愿不要将以下代码放在每个 HTTP GET 函数中。

if (!Request.IsAuthenticated)
{
     return RedirectToAction("LogOn", "Account");
}

【问题讨论】:

    标签: asp.net asp.net-mvc-3


    【解决方案1】:

    使用[Authorize] 属性http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx 标记您的控制器

    查看您的 web.config,默认情况下您应该启用表单身份验证 authentication mode="Forms" http://msdn.microsoft.com/en-us/library/eeyk640h.aspx

    也看这个问题ASP.NET MVC Authorization

    如果您想要自定义授权行为,请查看此处Customizing authorization in ASP.NET MVC

    【讨论】:

    • 我想从剃须刀页面的 onGet 函数中重定向,授权在页面(不是控制器)上不起作用
    • 也可以使用与 Razor 页面相同的属性“授权”
    【解决方案2】:

    您可以将[Authorize] 属性放在需要验证的每个操作上。

    另外,请确保此部分已在您的 Web.Config 中定义:

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    

    【讨论】:

    • 完全正确,只是为了澄清——这个配置部分应该放在“system.web”中。
    【解决方案3】:

    我刚试过这个:

    <!-- using custom auth with MVC redirect -->
    <authentication mode="None">
      <forms loginUrl="~/Home/Index"/>
    </authentication>
    

    尽管我使用的是自定义身份验证,但它仍然有效。但不确定超时 - [Authorize] 是否仍会使用表单身份验证的默认设置,否则它根本不会管理超时(自定义身份验证的首选行为)。

    【讨论】:

      【解决方案4】:

      我使用了下面的代码 sn-p,发现它非常优雅,不需要编写任何重定向语句。 MVC 根据表单登录页面配置处理重定向,并在成功登录/注册后,将用户发送回初始请求页面

       if (!User.Identity.IsAuthenticated)
       {
          //return new HttpUnauthorizedResult(); //This or the below statement should redirect the user to forms login page
          return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
       }
      

      【讨论】:

        猜你喜欢
        • 2015-06-26
        • 1970-01-01
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 1970-01-01
        • 2017-07-31
        • 1970-01-01
        相关资源
        最近更新 更多