How to easily redirect if not authenticated in MVC 3?

前端 未结 4 655
夕颜
夕颜 2021-01-01 14:00

I am brand new to ASP.NET, and I\'m trying to find a way to easily redirect an unauthenticated user from any page on the site to the logon page. I would prefer to not put th

4条回答
  •  盖世英雄少女心
    2021-01-01 14:14

    I used the below code snippet and found it to be very elegant not requiring to write any redirect statements. MVC takes care of the redirection based on the forms login page configuration and upon successfull login/registration, the user is sent back to the initial requested page

     if (!User.Identity.IsAuthenticated)
     {
        //return new HttpUnauthorizedResult(); //This or the below statement should redirect the user to forms login page
        return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
     }
    

提交回复
热议问题