简体   繁体   中英

Setting default page for asp.net core MVC application

I am currently learning asp.net core and I would like to set the login page as the first page the users see when they open the app, but only if they are not logged in yet, otherwise they should see the index page as per usual.

So far I found that I could get what I want by changing the method Configure in Startup.cs, specifically the inner method app.UseMvc , which looks like this

app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
});

I know that if I modify the property "template" to look for the Login controller and action would do the job. But the problem is, the login on my app was created by the framework Identity classes, therefore I can not reference the controller nor the action, because they don`t exist, what I have is a folder containing the files Login.cshtml and Login.cshtml.cs, which were scaffolded by the code-generator. The Login functionality works just fine, but not where I want it to.

So is there any way to reference the Login even if it is not a Action from a controller?

I dont know how much this will help , but you can try this

[AttributeUsage(AttributeTargets.Class |
 AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionTimeoutFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ISession session = filterContext.HttpContext.Session;

        if (session.GetString("UserID") == null)
        {
            var controller = filterContext.Controller as Controller;

            controller.TempData.Add("Msg", "Redirection to Login Page, Reasons : Session Timeout or Unauthorized access");
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary {
            { "Controller", "LogIn" },
            { "Action", "Index" }
                });
        }
        else
        {
        //redirect to dashboard or other page as per your need 
        }
        base.OnActionExecuting(filterContext);
    }
}

This is a custom filter , you can decorate your Login Controller with this. Now explanation

  • It will check session value , here it is UserID , you can use your session keys here , If session does not exist than it will redirect to login page
  • But if session exist than you can put a else statement to redirect on your dashboard screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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