如何限制对MVC5中某些操作的访问?

时间:2014-08-08 20:17:38

标签: c# mysql asp.net asp.net-mvc

我正在开发一个ASP.NET MVC5项目,其中MySQL(实际上更像是MariaDB)作为数据库和EF 6。 我决定使用" native"验证方法因为它使用了SQL Server,所以......好吧。我需要解决一些问题。

假设有一个名为" Persons"使用默认的EF的CRUDE。事实上,我希望默认的登录用户可以访问“详细信息”和“列表视图”,但不能访问“创建”,“删除”和“编辑”视图。所以,根据SO中的一些答案,我提出了"解决方案" :

创建一个继承Controller类的抽象类,并在OnActionExecuting定义一个重写方法:

public abstract class InternalAreaBaseController: Controller {
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if ( Session["UserObj"] == null ) {
            Response.Redirect( @"~\AcessoNegado\Desconectado" );
        }
        else{
            base.OnActionExecuting( filterContext );
        }

    }
}

我在public class PersonsController : InternalAreaBaseController中完成了所需的继承,它的工作原理如下: 如果当前会话不包含" UserObj" object,它基本上检测用户是否连接,重定向到" Disconnected"错误页面。

但是,这仅检查用户是否已连接;在PersonsController内,所有用户都可以访问操作public ActionResult Index(),但还有一个操作public ActionResult Create()只能由用户在确定的条件下访问。

有没有办法在PersonController:InternalAreaBaseController旁边传递一个标志,以便抽象类知道何时阻止确定的用户?

喜欢的东西

public abstract class InternalAreaBaseController: Controller {
public int AccessDegree { get;  set; }
public User? SessionData = Session["UserObj"];
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{

       if ( SessionData == null ) {
           Response.Redirect( @"~\AcessoNegado\Desconectado" );
       }
       elseif(SessionData.AccessDegree<AccessDegree){
            Response.Redirect( @"~\AcessoNegado\SemCredenciais" ); //NotEnoughCredentials
       }
       else{
           base.OnActionExecuting( filterContext );
       }

    }
}

1 个答案:

答案 0 :(得分:0)

你可以这样使用。

public ActionResult Login()
{
   bool IsValidUser = // Check User Credential
   if(IsValidUser) // If it is valid
   {
      FormsAuthentication.SetAuthCookie("username", false);
      return RedirectToAction("Index");
   }
   else
   {
      //Show the message "Invalid username or password"
   }

}

在控制器中,

[Authorize]
public ActionResult Index()
{
   // Do something
}
相关问题