简体   繁体   中英

how to redirect to login page if user directly entres URL in browser using ASP.NET

I am working on asp.net entity framework. I want to access the pages only through login and not directly by entering the URL of the page. If user enters the URL of the page and tries to access it then he should be redirected to Login Page. How can I do that? User are supposed to login with username and password from DB. I am new to ASP.NET

The functionality you are looking for can be achieved by adding the following authentication/authorization sections to the ASP.NET Web.config file like shown in the following example:

<system.web>
  <authentication mode="Forms">
    <forms name="SomeName" 
           loginUrl="Login.aspx" 
           protection="All" 
           path="/">
    </forms>
  </authentication>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

It essentially denies all access for unauthenticated Users: if such unauthenticated User tries to access any page at your website, then he/she will be redirected to the Login.aspx page ( details at MSDN https://msdn.microsoft.com/en-us/library/wce3kxhd.aspx , https://msdn.microsoft.com/en-us/library/xdt4thhy.aspx ).

Hope this will help.

If you are using the asp.net Identity to log users in (I believe this is the default for new MVC project) then you can use the data annotations to set this functionality at the controller. It should look something like

//GET
[Authorize]
public ActionResult Index(){
    return View();
}

This may do what you want automatically. If you end up needing to explicitly define where the Authorize attribute will redirect the user there is a good answer here.

Use Session variable. As soon as the user logs in , create a session variable and store some value in it. At each page page load event put an if condition on whether the session variable exists.In the else condition, redirect the user to the login page.At every logout , release the session variable.

You can try this in behind code

        if (User.Identity.IsAuthenticated == true)
        {
            Response.Redirect("The Page you want");
        }

        else
            Response.Redirect("Login.aspx"); // redirect it to your login page

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