ASP.Net MVC 3 Redirect UnAuthorized User not to loginUrl

ntep vodka picture ntep vodka · Oct 5, 2011 · Viewed 24.6k times · Source

i have a project using ASP.Net MVC3 and using membership for roles. i use authorize in every controller. eg:

[Authorize(Roles = "Administrator")]
    public ActionResult Index(string q, int i)
    {
      return View(model);
    }

if someone doesnt have role for administrator, then it will redirect to login page by default. how to change it,so it will redirect into Views/Shared/UnAuthorize.cshtml ? or maybe if someone doesnt have role for administrator, it will show message box (alert) ?

thanks in advance.

Answer

ntep vodka picture ntep vodka · Oct 6, 2011

i solved my problem. i only do this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

public class MyAuthorize : AuthorizeAttribute
{
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
     //you can change to any controller or html page.
     filterContext.Result = new RedirectResult("/cpanel/roles/unauthorize");

   }
 }

and apply MyAuthorize to class or action:

[MyAuthorize]
public class AdminController :Controller
{
}

thats it.