开发者

How to display attribute error messages

I am having an attibute

public class RequiresAdminRights : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            User user = User.Load(HttpContext.Current.User.Identi开发者_如何转开发ty.Name);
            if (user != null)
            {
                if (!(user.IsInRole(Role.Administrator)))
                    throw new Exception("You need admin rights to access this resource.");
            }
        }
    }

In my controller I have

[Attributes.RequiresAdminRights]
public class UserController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

The user logged in doesnt have any admin right and the RequiresAdminRights throws an exception. How can I display the exception message?


Throw a custom exception like PermissionDeniedException, create a base Controller class and define like this.

[HandleError(ExceptionType = typeof(PermissionDeniedException), View = "Login")]]
public class BaseController : Controller
{

}

Your controller should now extend this class. Also, don't forget to turn On the customErrors in your web.config.

Now, everytime you throw and PermissionDeniedException the user will be redirected to "Login" View. Another option is to redirect the user to a "Permission Denied View" that will explain to your user that he needs to log in before accessing that page.

For more details you can check this other SO questions.

  1. ASP.NET MVC HandleError
  2. ASP.net MVC [HandleError] not catching exceptions
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜