NET MVC mode to determine whether users log in or not

Posted by dmcentire on Tue, 30 Jun 2020 05:42:32 +0200

In our daily development of the vast majority of systems, are involved in the management of user login and authorization issues. Authentication is open to all users, while authorization is open to certain user roles.

stay asp.net In MVC, although Microsoft has helped developers build ASP.NET Identity is such a powerful authentication and authorization framework, but if you want to customize more logical functions, you have to do it yourself.

According to the daily development experience, I summarized the following two methods:

1. Inherit Controller:

1.1 in my earliest days, it was relatively simple, perhaps learned from WebForm. I didn't read all the methods in the Controller, so I added my own verification method in the derived class, and then called it in each Action method. This method seems to be a little painful now

The derived classes are as follows:

public class AuthenticationControllor : Controller
{
    public bool Validate()
    {
        if (Session["username"] == null)
            return false;
        else
            return true;
    }

    public ActionResult RedirectLogin(bool redirect = true)
    {
        if (redirect)
            return RedirectToAction("Login", "Home", new { from = Request.Url.ToString() });
        else
            return RedirectToAction("Login", "Home");
    }
}

The usage classes are as follows:

public class HomeController : AuthenticationControllor
{
    public ActionResult Index()
    {
        if (!Validate())
            return RedirectLogin();
 
        return View();
    }
}

1.2 after learning many people's code, I found that there was an OnActionExecuting method in the Controller, which was executed before the Action, which was very convenient.

The derived classes are as follows:

public class AuthenticationControllor : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["username"] == null)
            filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
            
        base.OnActionExecuting(filterContext);
    }
}

The usage classes are as follows:

// You don't need to write any more logic code to determine whether to log in and jump
public class HomeController : AuthenticationControllor
{
    public ActionResult Index()
    { 
        return View();
    }
}

2. Inherit ActionFilterAttribute:

Since the inherited Controller method is not suitable for scenarios where some actions under a Controller need to be logged in and some actions do not need to log in, it is better to write a unified feature for each Action.

ActionFilterAttribute also has OnActionExecuting method. Like Controller, it abstracts and implements IActionFilter interface.

The derived classes are as follows:

// Login authentication features
public class AuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["username"] == null)
            filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
            
        base.OnActionExecuting(filterContext);
    }
}

The usage is as follows:

public class HomeController : Controller 
{ 
    [Authentication] 
    public ActionResult Index()
    {
        return View();
    }
}

If you want to use this filter for all actions of the entire MVC project, the steps are as follows:

a. Ensure Global.asax.cs Application of_ The start method contains the following red lines:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

b. In FilterConfig.cs Register the corresponding feature filter in the file:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthenticationAttribute());
    }
}

Reprinted: https://www.xjqyc.cn/blog/1331.html

Topics: Session