ASP.NET MVC: Custom Authorize Attribute
By FoxLearn 5/29/2017 7:23:19 PM 7.47K
How to Custom authorize attribute with ASP.NET Identity MVC 5 using C#, Entity Framework Code First
Step 1: Open Shared folder, then create a AuthorizeFailed view as below
@{ ViewBag.Title = "Authorize Failed"; } <h2>AuthorizeFailed</h2> <p>@ViewData["Message"]</p>
Step 2: Create a CustomAuthorizeAttribute class, then add code as below
[AttributeUsage(AttributeTargets.Method)] public class CustomAuthorizeAttribute : AuthorizeAttribute { public string ViewName { get; set; } public CustomAuthorizeAttribute() { ViewName = "AuthorizeFailed"; } public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); IsUserAuthorized(filterContext); } void IsUserAuthorized(AuthorizationContext filterContext) { //user is authorized if (filterContext.Result == null) return; if (filterContext.HttpContext.User.Identity.IsAuthenticated) { ViewDataDictionary dic = new ViewDataDictionary(); dic.Add("Message", "You don't have sufficient privileges for this operation !"); var result = new ViewResult() { ViewName = this.ViewName, ViewData = dic }; filterContext.Result = result; } } }
Step 3: Open HomeController, then change code as below
public class HomeController : Controller { public ActionResult Index() { return View(); } [CustomAuthorize(Roles = "Admin")]//user 1 public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } [CustomAuthorize(Roles = "Sales")]//user 2 public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } }
VIDEO TUTORIALS
- ASP.NET MVC Responsive Templates Free Download
- How to upload file in ASP.NET MVC
- How to Create Contact Form Flat Responsive in ASP.NET MVC
- How to check if HttpPostedFileBase is an image
- How to upload Multiple File in ASP.NET MVC
- ASP.NET MVC: Implement Password Reset with ASP NET Identity
- ASP.NET MVC: Getting Started
- ASP.NET MVC: Create Custom Routes
Categories
Popular Posts
Material Lite Admin Template
11/14/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024
Modular Admin Template
11/14/2024
Monster Admin Template
11/14/2024