默认情况下,AuthorizeAttribute
类是System.Web.Mvc
命名空间的一部分(请参阅Github存储库:aspnetwebstack)。该方法导致了登录重定向有HandleUnauthorizedRequest
:
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
filterContext.Result = new HttpUnauthorizedResult();
}
HTTP以上从方法401的状态码的响应将触发FormsAuthenticationModule
(见下文参考),其中OnLeave
方法重定向与包括FormsAuthentication.ReturnUrlVar
属性登录网址:
strRedirect = loginUrl + "?" + FormsAuthentication.ReturnUrlVar + "=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding);
// Do the redirect
context.Response.Redirect(strRedirect, false);
要覆盖此行为(包括删除ReturnUrl
部分),请创建授权类,从AuthorizeAttribute
类延伸,例如(这是一个示例实现):
using System.Web.Mvc;
using System.Web.Routing;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// @Override
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new { controller = "Account",
action = "Login"
}));
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
然后,您可以实现这样一个自定义的授权属性:
[CustomAuthorizeAttribute]
public ActionResult UserPage()
{
return View();
}
注:使用AuthorizeAttribute
上的所有网页,需要用户登录认证,对登录页面改为使用AllowAnonymousAttribute
。
相关参考资料:
System.Web.Security.FormsAuthenticationModule (MS Github reference)
What initially sets the ReturnUrl parameter when using AuthorizeAttribute
Generate a return Url with a custom AuthorizeAttribute
How to remove returnurl from url?
检查控制器文件夹中的AccountController.cs的你的项目 – Shiham
代码段中显示从AccountCon复制troller.cs。但是我无法找到任何与ReturnUrl相关的代码。 –
详细问题:我为ForgetPassword创建了一个页面,并且在那里添加了登录页面的链接。当我重定向回登录页面时,没有ReturnUrl参数被添加到url。 @ Html.ActionLink(“进入登录页面”,“登录”,“帐户”),我已经使用此代码在ForgetPassword页面中创建一个到登录页面的链接。 –