在我的.NET MVC 4中,我添加了一个全局过滤器以保护我的控制器。 这是使用:
完成的public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
从我的Global.cs类中调用。
我的Web.config文件包含标准配置:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
我的登录操作以[AllowAnonymous]
修饰,以允许匿名用户登录。
到目前为止,一切都很好。这是我的登录操作:
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
现在,我想添加一个重置密码页面,这也就像匿名用户可以使用登录页面一样。我创建了我的动作(在Login动作的同一控制器下)并用[AllowAnonymous]
装饰进行装饰:
[AllowAnonymous]
public ActionResult ResetPasswordForUser(string message = "")
{
ViewBag.message = message;
return View();
}
然后创建相应的视图。
我将此链接添加到我的登录页面:
@Html.ActionLink("Forgot your password?", "ResetPasswordForUser", "Account")
在运行时,当我使用匿名用户单击此链接时,我会进入ResetPasswordForUser操作,但是在返回视图时,将调用Login操作,我实际上无法访问所需的视图。出于某种原因,即使我使用[AllowAnonymous]装饰,我的请求也会被截获。
我在这里错过了什么吗?
提前致谢
UPDATE1:
根据Darin Dimitrov请求添加我的ResetPasswordForUser视图:
@using TBS.Models
@model TBS.ViewModels.ResetPasswordForUserViewModel
@{
ViewBag.Title = "Reset Password";
}
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<table class="edit-table rounded bordered" style="width: 400px">
<tr>
<td class="label-td">
@Html.LabelFor(m => m.Username)
</td>
<td>
@Html.TextBoxFor(m => m.Username)
@Html.ValidationMessageFor(model => model.Username)
</td>
</tr>
<tr>
<td class="label-td">
@Html.LabelFor(m => m.Password)
</td>
<td>
@Html.Password("Password")
@Html.ValidationMessageFor(model => model.Password)
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<input type="submit" value="Reset" />
</td>
</tr>
</table>
}
答案 0 :(得分:11)
ResetPasswordForUser
视图使用的_Layout文件是否可能在您的控制器中调用一个尚未使用AllowAnonymous
修饰的操作?
这会导致这种行为。
答案 1 :(得分:3)
听起来你的布局中可能有一个非匿名的@ Html.Action或Html.RenderAction,这会导致你的页面重定向到登录。
编辑:删除旧答案,因为它不正确,对于任何人来看都没用。
答案 2 :(得分:1)
我不知道添加全局授权过滤器是否与AllowAnonymous冲突。我设置项目的方法是让一个基本控制器在控制器级别设置[Authorize]属性。
我的所有控制器都继承自这个BaseController,除了那些需要匿名访问的控制器,通常是我的AccountController和我的MarketingController。那些只是继承自Controller,然后我可以在Action级别设置[Authorize]。