Dan An
Dan An

Reputation: 424

Asp.net access sessionstate from JavaScript

Our system using HttpContext.Current.Session("Client") to store the current user info.

One property in the session is a roleID i.e. CType(HttpContext.Current.Session("Client"), Client).RoleId

By checking the value of RoleId, the system can identify whether the user can access a couple of pages.

I've validated it in the server-side. But for the easiest way to present the Notice Message I think is using JavaScript.

So is it possible to get the session value in JavaScript (even in a external JavaScript)? How about Cookie? What is the drawback for adding Cookies for an existing system?

And any other suggestions if you have.

Thx

Yes, I did the validation in server side. Later again, I'll add restrictions in DBs as well.

Result:

I used webMethod inside a web service, caz it is a Master Page.

Thanks for you answer.

but another issue raised:

Trigger/Prevent page event by using asynchronous webmethod return value in JavaScript

please give me some advise on that question as well, thx.

Upvotes: 0

Views: 2003

Answers (3)

Daniel A. White
Daniel A. White

Reputation: 190952

You could do it as a cookie, but it would slow down your round trip for every resource. Hence, I don't recommend this approach.

One option is to have a dynamic page that returns a javascript object in global with the appropriate variables printed out. You then could just include it as a standard script tag.

Another approach is to make an AJAX call.

Keep in mind, you should still always validate the base request and never trust the client.

Upvotes: 1

Antonio Bakula
Antonio Bakula

Reputation: 20693

You can make ashx page or WCF service and call that with javascript. But don't return roleID and check that ID on client, instead just return true / false if user has access. Use jQuery ajax call to ashx or WCF service, you should find tons of examples on google

Upvotes: 0

Chris Gessler
Chris Gessler

Reputation: 23113

Sending roles to the client and using JavaScript for business logic based upon these roles is a security risk. Users (hackers) know how to manipulate client-side code to gain access to things they're not supposed to.

I recommend sending down only the content the user has access to or use AJAX to retrieve the content dynamically from the client.

But to answer your question, no, you cannot retrieve session data directly from the client.

Upvotes: 0

Related Questions