Sna*_*yes 21 c# asp.net asp.net-mvc asp.net-mvc-3
我读了
如果在MVC 3中未经过身份验证,如何轻松重定向?当用户未获得授权但来自答案的链接(表示http://wekeroad.com/2008/03/12/aspnet-mvc-securing-your-controller-actions/)不起作用时, 将重定向到AccessDenied页面.
我放
[Authorize(Users = "test")]
public class RestrictedPageController: Controller
{
public ActionResult Index()
{
return View();
}
....
}
Run Code Online (Sandbox Code Playgroud)
在我的web.config中,我已经
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
Run Code Online (Sandbox Code Playgroud)
但是当我想要访问时/RestrictedPage/Index
,它必须将我重定向到其他页面(来自其他控制器).而不是这个,错误看起来像:
Server Error in '/Project' Application.
The view 'LogOn' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Account/LogOn.aspx
~/Views/Account/LogOn.ascx
~/Views/Shared/LogOn.aspx
~/Views/Shared/LogOn.ascx
~/Views/Account/LogOn.cshtml
~/Views/Account/LogOn.vbhtml
~/Views/Shared/LogOn.cshtml
~/Views/Shared/LogOn.vbhtml
Run Code Online (Sandbox Code Playgroud)
登录前,Logon
页面窗体正确显示,但访问/RestrictedPage/Index
页面时出现上述错误.我可以使用授权访问RestrictedPage
页面的用户登录.
我的错误在哪里以及如何设置重定向?
VJA*_*JAI 56
默认Authorize
属性的行为方式是,当用户未经过身份验证或身份验证但未经授权时,它会将状态代码设置为401(UnAuthorized).当过滤器将状态代码设置为401时 ,ASP.NET框架会检查网站是否启用了表单身份验证,如果是,则重定向到loginUrl
那里的参数设置.
如果要更改该行为,则表示要将用户重定向到AccessDenied
控制器(如果用户已通过身份验证但未授权),则必须扩展该Authorize
属性并覆盖该HandleUnauthorizedRequest
方法.
对于前者
public class CustomAuthorize: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "AccessDenied" }));
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以HandleUnauthorizedRequest
根据需要覆盖,然后必须标记控制器操作以使用CustomAuthorize
属性而不是内置属性.
我喜欢Mark's Answer,
但我不想将所有动作属性
从[Authorize]更改为[CustomAuthorize]
我编辑Login()
动作AccountController
并Request.IsAuthenticated
在
我认为的显示视图之前进行检查,如果通过身份验证的用户转到/Account/Logon
,
我将重定向到/Error/AccessDenied
。
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("AccessDenied", "Error");
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
50638 次 |
最近记录: |