[英]How do I restrict access to some actions in MVC5?
我正在开发一个ASP.NET MVC5项目,使用MySQL(实际上更像MariaDB)作为数据库和EF6。我决定不使用“本机”身份验证方法,因为它使用了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”对象(该对象基本上检测到用户是否已连接),则重定向到“ 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 );
}
}
}
您可以使用这种方式。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.