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

天涯浪子 提交于 2019-12-07 23:05:38

问题


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


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/36719517/how-to-redirect-to-login-page-if-user-directly-entres-url-in-browser-using-asp-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!