处理MVC3中的PrincipalPermission异常

时间:2012-09-26 15:15:33

标签: asp.net-mvc-3 exception exception-handling principalpermission

在我的MVC应用程序中,我使用以下方法修饰了控制器的一些方法:

[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public ActionResult Create(FormCollection collection)
{
    try {
             ...
    }
    catch {
        return View();
    }
}

事实上,如果我没有登录或没有正确的角色,MVC应用程序会抛出异常。问题是我没有将应用程序重定向到错误页面。

我尝试像这样创建一个基本控制器:

[HandleError]
public class BaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        // Make use of the exception later
        this.Session["ErrorException"] = filterContext.Exception;

        // Mark exception as handled
        filterContext.ExceptionHandled = true;

        // ... logging, etc

        // Redirect
        filterContext.Result = this.RedirectToAction("Error", "Home");

        base.OnException(filterContext);
    }

}

然后在Home控制器中添加Error视图以及实际的View。问题是当我在Visual Studio中尝试这个时,我首先在输入受保护的操作方法时遇到异常:

 SecurityException was unhandled by the application

然后我必须执行Debug | Continue,然后才重定向到Error视图,但这在生产应用程序中是不可接受的,因为它应该直接进入Error视图。

1 个答案:

答案 0 :(得分:1)

只是想知道为什么你不只是使用标准的AuthorizeAttribute。很确定它会做同样的事情而且只是工作吗?

E.g。

[Authorize(Roles="Administrator")]
public ActionResult Create(FormCollection collection)

关于一般MVC安全的文章。 http://www.codeproject.com/Articles/288631/Secure-ASP-NET-MVC3-applications

相关问题