C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Custom Authorize Attribute In MVC
WhatsApp
Ankit Kanojia
Jun 22
2016
2
k
0
0
//Create A CheckAuthorization.cs File In Your MVC Project
public
class
CheckAuthorization: AuthorizeAttribute {
//Check Cookie For Unique Field && Check IsAuthenticated Attribute
if
(HttpContext.Current.Session[
"UserID"
] ==
null
|| !HttpContext.Current.Request.IsAuthenticated) {
if
(filterContext.HttpContext.Request.IsAjaxRequest()) {
filterContext.HttpContext.Response.StatusCode = 302;
//Found Redirection to another page. Here- login page. Check Layout ajaxError() script.
filterContext.HttpContext.Response.End();
}
else
{
filterContext.Result =
new
RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl +
"?ReturnUrl="
+
filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
}
}
else
{
//code for page level authorization
}
}
//Now, just i have to put [CheckAuthorization] attribute on my controller to access my CheckAuthorization Function which is Custom Authorize Attribute.
//Add authentication mode to Your Web.config
//Add Below Code To Your Web.confing
<
system.web >
<
authentication mode =
"Forms"
>
<
forms loginUrl =
"~/Account/Login"
timeout =
"2880"
/ >
//Declare Your Return URL Here. Mean If Login Fail Then Page Redirect This URL
<
/authentication> <
/system.web>
Custom Authorize Attribute
MVC
Up Next
Custom Authorize Attribute In MVC