开发者

ASP.NET MVC2 handle controller's UnauthorizedAccessException

I need to use more complicated authorization, so I created class which can throw UnauthorizedAc开发者_开发技巧cessException when user don't have permission for action. But how should I handle this exception correctly? I need redirect to login page when this exception is thrown so I think I cannot use controller's OnException method. As temporary solution I use this:

public abstract class MyController : Controller
{    
    protected override void ExecuteCore()
    {
        try
        {
            base.ExecuteCore();
        }
        catch (UnauthorizedAccessException)
        {
            HttpContext.Response.StatusCode = 401;
        }
    }
}

It seems it could work, but I am not sure if it is proper solution.

Thanks for tips.


You can also use an override of HandleErrorAttribute to perform custom logic on an unhandled exception from your controller.

public class MyErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        // Do Whatever
    }
}

And your controller:

[MyError]
public class SampleController : Controller { }


Simply decorate your controller action with the [Authorize] attribute or set the response status code to 401 in your controller actions. The ASP.NET framework will do the job to automatically redirect you to the login page.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜