Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5asp.net-identity

Show views based on authentication status in asp.net mvc


If user is logged in I want to show my department view, if not logged in want to show login page. I have tried something like this inside my RouteConfig

  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
          if (HttpContext.Current.User==null)
        {
            routes.MapRoute(
              name: "Default",
              url: "{controller}/{action}/{id}",
              defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
                );
        }
        else
        {
            routes.MapRoute(
             name: "Default",
             url: "{controller}/{action}/{id}",
             defaults: new { controller = "Department", action = "Index", id = UrlParameter.Optional }
               );
        }

    }

But this one always loads login page at startup.Can anyone point out what I am doing wrong here? Note: I am using Asp.net Identity for this application


Solution

  • Your HttpContext.Current.User==null logic would go in the controller, not your route registration

    Note- the correct call is Request.IsAuthenticated

    Assuming you have an action method like this:

    public ViewResult Index()
    {
      if(Request.IsAuthenticated)
        return new RedirectResult("toLoginPage")
      else
        return new View("loggedInView");
    }
    

    However, I believe the [Authorize] attribute could be what you want in your use case: (note - having re-read the question, this may not be accurate, as you want to return a different view based on login status)

    [Authorize]
    public ViewResult ShowPerson(int id)
    {
        return new View("loggedInView");
    }
    

    And in your web.config, something like

    <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" />
    </authentication>
    </system.web>
    

    In this particular instance, with the [Authorize] attribute above the action method, if the user is not logged in, they'd be redirected to log in.