简体   繁体   中英

How to create re-direct to login page in ASP.NET?

Using ASP.NET, what is the best way to re-direct a user to my login page, if they attempt to visit a page that's meant for logged-in users?

Note: Not sure if this matters, but I'm using ASP.NET WebForms, but I'm not actually using any WebForms. The front end is pure jQuery/HTML/CSS that communicates using jQuery $.getJSON() or $.post() with backend *.ashx files

Do I have to add code to the Page_Load() event of my form? Or is there central "redirector" sort of file that I can use?

Thanks!

Definitely don't do it in Page_Load, that violates the DRY principle . You can use <location> elements in your web.config to require authorization to certain pages or directories in your site, as described here .

Example:

<location path="admin"> 
  <system.web> 
    <authorization> 
      <allow users="John"/> // allow John ..note: you can have multiple users seperated by comma e.g. John,Mary,etc or you can allow roles
      <deny users="*"/>  // deny others 
    </authorization>
  </system.web>
</location

You can easily implement this in global.asax. We use it in our app to check to see if the user is logged in and if not redirect to the login page. The events in global. Asax are all application level events, so you get things like request start/end and can easily plug into the pipeline.

You should handle this in the global.asax (HttpApplication class file) - specifically like so:

c#

void Application_OnAuthenticateRequest(Object Source, EventArgs Details) {
         // Authentication code goes here.
         //if fail, Response.Redirect('NotAuthenticated.htm');
         //or like so.
 }

VB

 Sub Application_OnAuthenticateRequest(Source As Object, Details as EventArgs)
         'Authentication code goes here.
     End Sub

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