我读过
How to easily redirect if not authenticated in MVC 3?和Redirect to AccessDenied page when user is not authorized,但答案中的链接(表示http://wekeroad.com/2008/03/12/aspnet-mvc-securing-your-controller-actions/)不起作用。
我把
[Authorize(Users = "test")]
public class RestrictedPageController: Controller
{
public ActionResult Index()
{
return View();
}
....
}
在我的web.config中,我已经
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
相应地使用https://stackoverflow.com/a/6770583/998696
但是当我想访问/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
登录前,Logon
页面表单显示正确,但在访问/RestrictedPage/Index
页面时出现上述错误。我可以用不同的用户登录,一个授权访问RestrictedPage
页面。
我的错误在哪里?如何设置重定向?
发布于 2015-07-22 15:31:37
我喜欢马克的回答
但是我不想更改我所有的操作属性
从Authorize到CustomAuthorize
我在AccountController
上编辑Login()
操作
并在显示视图之前检查Request.IsAuthenticated
我认为,如果通过身份验证的用户访问/Account/Logon
,
我将重定向到/Error/AccessDenied
。
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("AccessDenied", "Error");
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
发布于 2012-06-07 17:36:31
将"/Account/LogOn“替换为"~/Account/LogOn”
发布于 2017-03-10 16:08:12
因为我不想覆盖AuthorizeAttribute
,所以我使用了过滤器
public class RedirectFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!IsAuthorized(filterContext))
{
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary(new {controller = "AccessDenied"}));
}
}
private bool IsAuthorized(ActionExecutingContext filterContext)
{
var descriptor = filterContext.ActionDescriptor;
var authorizeAttr = descriptor.GetCustomAttributes(typeof(AuthorizeAttribute), false).FirstOrDefault() as AuthorizeAttribute;
if (authorizeAttr != null)
{
if(!authorizeAttr.Users.Contains(filterContext.HttpContext.User.ToString()))
return false;
}
return true;
}
}
https://stackoverflow.com/questions/10928277
复制相似问题