The code order is: Onauthorization-->authorizecore-->handleunauthorizedrequest
Assuming that Authorizecore returns false, the Handleunauthorizedrequest method will be gone, and Request.stauscode will return a 401,401 error and corresponding in Web. config
Of
<authentication mode= "Forms" >
<forms loginurl= "~/" timeout= "2880"/>
</authentication>
All, Authorizecore==false, jumps to the loginurl= "~/" defined in Web. config
public class Checkloginattribute:authorizeattribute
{
protected override bool Authorizecore (HttpContextBase HttpContext) {
BOOL Pass = false;
if (! Checklogin.adminlogincheck ())
{
HttpContext.Response.StatusCode = 401;//No permission status code
Pass = false;
}
Else
{
Pass = true;
}
return Pass;
}
protected override void Handleunauthorizedrequest (AuthorizationContext filtercontext)
{
if (FilterContext.HttpContext.Request.IsAjaxRequest ())
{
if (! App.AppService.IsLogon)
{
Filtercontext.result = new Jsonresult
{
Data = new {issuccess = false, Message = "Sorry, login timeout, please login again!"},
Jsonrequestbehavior = Jsonrequestbehavior.allowget
};
Return
}
}
if (App.AppService.IsLogon)
{
Return
}
Base. Handleunauthorizedrequest (Filtercontext);
if (FilterContext.HttpContext.Response.StatusCode = = 401)
{
Filtercontext.result = new Redirectresult ("/");
}
}
}
Authorizeattribute's Onauthorization method internally calls the Authorizecore method, which is where the validation and authorization logic is implemented, assuming that this method returns True,
Indicates a successful authorization, assuming that it returns false, indicating an authorization failure, which sets a httpunauthorizedresult to the context, and the result of this actionresult run is to return to the browser
A 401 status code (not authorized), but the return status code is not interesting, generally jump to a login page, can rewrite the Authorizeattribute
Handleunauthorizedrequest
protected override void Handleunauthorizedrequest (AuthorizationContext context)
{
if (context = = null)
{
throw new ArgumentNullException ("Filtercontext");
}
Else
{
String path = context. HttpContext.Request.Path;
String strURL = "/account/logon?returnurl={0}";
Context. HttpContext.Response.Redirect (String. Format (strURL, Httputility.urlencode (Path)), true);
}
}
Using Authorizeattribute as an authentication operation in MVC