1

在我的 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 视图。

4

1 回答 1

1

只是想知道为什么您不只是使用标准 AuthorizeAttribute。很确定它会做同样的事情并且可以正常工作吗?

例如

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

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

于 2012-09-28T00:26:13.753 回答