1

At the page load I want to check Request.IsAuthenticated. How can I do it through javascript. The code below shows how I did it in asp.net c#?

if (!Request.IsAuthenticated)
{
     Response.Redirect("~/Login.aspx");
}
2

3 Answers 3

3

If you are using ASP.NET MVC then you can do like following.

 <script>
     var isRequestAuthenticated=' @Request.IsAuthenticated';
 </script>

Else if you are using normal ASP.NET Web forms

 <script>
     var isRequestAuthenticated='<%=Request.IsAuthenticated%>';
 </script>

Now you can use that variable to check whether this request is authenticated or not.

Sign up to request clarification or add additional context in comments.

3 Comments

Try asp.net webform. I have given both options read it carefully
I am using a webform were there is no code behind. All the functionalities in javascript file. It tried your code in page load of Javascript but it always returns true regardless whether logged in or logged out.
On the webforms example, C# will render "False". And because non-empty strings are truthy in javascript, writing if(isRequestAuthenticated){foo();} will execute foo() if isRequestAuthenticated == "False". I took out the single quotes and added .ToString().ToLower().
1

This should work:

    <script type="text/javascript">

        function foo(){
            if('@Request.IsAuthenticated' === 'True') {
                // your implementation for authenticated users go here

            }
            else{
                // your implementation for not authenticated users....
                //e.g. alert('You must be logged in to do bla bla bla');
            }
        }
    </script>

Comments

0

By JavaScript, I assume that you mean using AJAX so that the value is read directly into your JavaScript.

Response.Write(Request.IsAuthenticated ? "TRUE" : "FALSE");

This will return "TRUE" if true, "FALSE" if false. Put this into a method that only your AJAX function calls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.