简体   繁体   English

C#,ASP.NET-限制对控制器方法的访问

[英]C#, ASP.NET - Restricting Access to Controller Methods

I'm constructing an ordering system of sorts that requires users to log in before proceeding to the main ordering part of the website. 我正在构建一种排序系统,要求用户先登录才能进入网站的主要订购部分。 For example, I have a login controller that (if the user exists in the database) assigns their ID and UserName to a session. 例如,我有一个登录控制器(如果用户存在于数据库中)将其ID和UserName分配给会话。

public ActionResult Login(AccountAccess userObj)
{
    if (ModelState.IsValid)
    {
        using (SC_DBEntities db = new SC_DBEntities())
        {
            var accountObj = db.Users_Account.Where(u => u.Account_UserName.Equals(userObj.Account_UserName)).FirstOrDefault();
            if (accountObj != null)
            {
                var accessObj = db.Users_Access.Where(a => a.Account_ID.Equals(accountObj.Account_ID) && a.Access_Password.Equals(userObj.Access_Password)).FirstOrDefault();
                if (accessObj != null)
                {
                    Session["Account_ID"] = accountObj.Account_ID.ToString();
                    Session["Account_UserName"] = accountObj.Account_UserName.ToString();
                    return RedirectToAction("Index", "Home");
                }
            }
        }
    }
    return View(userObj);
}

What I want to do from here is block out access to other method actions if that Session is null. 我要从这里做的是,如果该Session为null,则禁止访问其他方法操作。 So for example, if they want to access the products page but they are not logged in, the will be redirected to the login page. 因此,例如,如果他们要访问产品页面但未登录,则将其重定向到登录页面。

I'm still reasonably new to ASP.NET so if there is a more efficient way of achieving this effect other than Sessions, please let me know. 我对ASP.NET还是很陌生,所以如果有除Sessions之外的更有效的方法来达到这种效果,请告诉我。

Could you not use a ActionFilterAttribute? 您可以不使用ActionFilterAttribute吗?

    public class CheckSession: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
           var MySession = HttpContext.Current.Session

           if(MySession["Account_ID"] == null || MySession["Account_UserName"]== null)
           {
              filterContext.Result = new RedirectResult(string.Format("/Account/"));
           }  
        }
    }

Then all you have to do is put it on your controller action - Can also put it on the controller to check all inside that controller: 然后,您所要做的就是将其放入控制器操作中-也可以将其放入控制器中以检查该控制器内部的所有内容:

[CheckSession]
public ActionResult Purchase()
{
 ....
}

To achieve what you want for a controller or a specific action, you should use custom filter or attributes ( In your case authorization attribute ). 要实现所需的控制器或特定操作,应使用自定义过滤器或属性(在您的情况下为授权属性)。

Please have a look to this good tutorial to begin : https://www.codeproject.com/articles/577776/filters-and-attributes-in-aspnet-mvc 请看看这个好的教程开始: https : //www.codeproject.com/articles/577776/filters-and-attributes-in-aspnet-mvc

After that, you just need to google : authorization attribute asp.net mvc 之后,您只需要google: 授权属性asp.net mvc

Based on your comment, you can use Sessions for the purpose you are asking for. 根据您的评论,您可以将Sessions用于所需的目的。 Assuming when a user logins, you store, say a username and their ID like you do above. 假设用户登录时,您像上面所做的那样存储并说出用户名及其ID。 If you want to make sure someone is logged in before running an action just check to see if those Session variables are null nor not. 如果要确保有人在执行操作之前已登录,则只需检查一下这些Session变量是否为null即可。

Going along with your Login Controller Code, suppose you have a purchase Controller Action: 连同您的登录控制器代码一起,假设您有购买的控制器操作:

public ActionResult Purchase()
{
    //Check to see if these values have been assigned via Login Controller Action
    if(Session["Account_ID"] == null || Session["Account_UserName"] == null)
    {
         //If so, redirect to Controller Action where user can log into.
         RedirectToAction("Index", "Account")
    }
    else
    {
         //Make Purchase occur.
    }
}

Identity is a newer and better login system, but has a pretty big learning curve in my experience. 身份是一个更新更好的登录系统,但根据我的经验,学习曲线很大。 Once you become more familiar with Sessions, I'd recommend to begin looking into Identity for future projects. 一旦您对Sessions更加熟悉,我建议您开始研究Identity以用于将来的项目。 Nothing "wrong" with Sessions, so for your purpose, the above code should work for actions you want users to be logged in to use. 会话没有问题,因此出于您的目的,以上代码应适用于您希望用户登录使用的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM