Session State not Retained over calls to a Page Method - asp.net

My server side code:
[WebMethod(CacheDuration = 0, EnableSession = true)]
public static int UserID()
{
if (HttpContext.Current.Session["UserID"] == null) return 0;
int UserID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
return (UserID);
}
My Client side code:
$.ajax({
type: "POST", cache: false,
url: "Login.aspx/UserID",
data: "{'r':" + rnd() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
This codes runs well on my localhost.
and the "UserID" ajax call, return the right value of the Session parameter.
but when i try to upload my website on the server, the "UserID" ajax call always returns false!!
my server is asp.net 2.0 and I'm using jquery 1.3.2
So please help to solve this problem.

Read this article: ASP.NET Session State FAQ
I found my answer in this questions:
Q: Session states works on some web servers but not on others.
A: Maybe machine name problem. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112 .
Q: Why are my Session variables lost frequently when using InProc mode?
A: Probably because of application recycle. See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q316148
Changing sessionState mode to "StateServer" solved the problem.
Use code below:
<sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424"
cookieless="false"
timeout="999"/>

A few things to check :
Are you using WebFarm configuration? there might be a problem when using session in WebFarm configuration.
Have you check your network traffic using tools like Fiddler or FireBug? Is ASP.NET Auth cookie sent during AJAX call?
Can you confirm your session var is valid?

Related

Web API session managment

My requirements - I have a web api whch gives me all data from db. I have a .net website which consumes this api to get all data. Now what I want is when I'm login my website I want to manage session in "API".
I know session in web api is not a good approach but still I need to do this.
I have already implemented session management in web api(taken reference from here) and its working fine if I'm sending all my request from postman(i.e. I'm setting variables in session by calling 1 method and retrieving that session variable by calling 2nd method). But when I'm doing the same from asp.net website with jQuery then I'm not getting stored session variable(what I noticed is I'm getting session id different every time-for each request).
code of saving variable in session
$.ajax({
url: 'http://localhost:63726/api/Login/Login',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
code of retrieving variable stored in session
$.ajax({
url: 'http://localhost:63726/api/SessionCheck/LoginName',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
What I need to do to achieve my goal..Your opinion will save my days...
I found my answer Session management in web api.
Please, read this Web Api Session storage before.
To retreive data from session use javascript sessionStorage (instead ajax).

How to make a session enabled ASP.NET web service work with an ajax client in a different domain?

Me and my work mate have spent lots of time finding this answer, so I thought I should share this self answered question.
I have a web service (ASP.NET 4.5) with a method that needs to use the session state. In order to archive this, I have decorated the method with EnableSession=true. This is what MS suggests to do in this article (See "Code Block A" at the end).
In order for the web service to be able to re-use the session, it needs to find a cookie with the session ID. This cookie is created and set, on the server side, by the web server itself the first time the method is called. In order to re-send this cookie with every call, MS suggests to use a "cookie container" that gets assigned to the web service proxy, saved between calls and reused with every call. (See "Code Block B" at the end).
This works great, as long as you plan to call the web service from the server side. I need to call it from the client side using a jQuery ajax JSON Post call (See "Code Block C" at the end). This code works great. In fact, the cookie with the session ID is passed to the web service automatically. No need of the cookie jar...as long as the client and the web service are on the same domain.
If the client is in a different domain (domaina.com) than the web service (domainb.com), the cookie with the session id is not passed along at all. As a result, every call to the web service is considered the first one.
I have the following headers defined on the web config to allow cross domain calls.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
So, what is missing?
Code Block A: Web Service with decorated method
public class Util: WebService {
[ WebMethod(EnableSession=true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int SessionHitCounter() {
if (Session["HitCounter"] == null) {
Session["HitCounter"] = 1;
}
else {
Session["HitCounter"] = ((int) Session["HitCounter"]) + 1;
}
return ((int) Session["HitCounter"]);
}
}
Code Block B: Server Side Cookie Jar Solution
<script runat="server">
void EnterBtn_Click(Object Src, EventArgs E)
{
// Create a new instance of a proxy class for your XML Web service.
ServerUsage su = new ServerUsage();
CookieContainer cookieJar;
// Check to see if the cookies have already been saved for this session.
if (Session["CookieJar"] == null)
cookieJar= new CookieContainer();
else
cookieJar = (CookieContainer) Session["CookieJar"];
// Assign the CookieContainer to the proxy class.
su.CookieContainer = cookieJar;
// Invoke an XML Web service method that uses session state and thus cookies.
int count = su.PerSessionServiceUsage();
// Store the cookies received in the session state for future retrieval by this session.
Session["CookieJar"] = cookieJar;
// Populate the text box with the results from the call to the XML Web service method.
SessionCount.Text = count.ToString();
}
</script>
Code Block C: Ajax Call
$.ajax({
type: "POST",
url: web_services_url + "/SessionHitCounter",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
After hours of thinking and Google searching my mate found that we were missing
An extra header ("Access-Control-Allow-Credentials")
Changing the "*" on "Access-Control-Allow-Origin" to the specific domain that is calling the web service
Adding an extra parameter on the ajax call (withCredentials)
These are the headers that are required to enable CORS
<add name="Access-Control-Allow-Origin" value="http://localhost:53710" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Credentials" value="true" />
This is the ajax call with the extra parameter
$.ajax({
type: "POST",
xhrFields: { withCredentials: true },
url: web_services_url + "/SessionHitCounter",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});

Persisting Session State via multiple request using jQuery $.ajax()

just been trying to recieve the session value from multiple jquery ajax requests on the same domain name. i think i understand that each request is kind of a virtual browser request so the session is mutally exclusive to each request, but there must be a way some how, has anyone solved this. Basically this is what im trying to do:
I have tries using type: GET and POST but still no luck.
Can anyone help please, Thanks?
First request - Stores the product id in a session
$.ajax({
url: 'http://localhost/websitetest/test.aspx?storeproduct=' + productid,
type: 'GET',
async: true,
success: function(data) {
}
});
Second Request - From the callback variable "data" recieves the product id from the session
$.ajax({
url: 'http://localhost/websitetest/test.aspx,
type: 'GET',
async: true,
success: function(data) {
var productID = data;
}
});
There is no question to send ajax request while accessing Session variable from asp page.
Simply you can do is :
<%
String session_var = Session("name_of_session_variable");
%>
Even if you still want to try Ajax, I think you will need to print the session variable in test.aspx file using Response.Write(), which will automatically return the content.
Please check this for further reference.
Please correct me as well if I am wrong.
Thank you.

calling asmx web service from jQuery

I am not able to call web service(asmx) from jQuery function.
It is saying "access denied" error while calling web service. It is working in the dev and local machine but I am getting the same error.
Here is my ajax call
$.ajax({
type: "POST",
url: "http://server.com/calculator.asmx/calculus",
data: "{ 'userID': '" + $("#usrid").val() + "','password': '" + $("#password").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
My web service is
[WebService(Namespace = "http://www.company.com/webservices/calculus")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class calculator : System.Web.Services.WebService
{
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet=false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public bool calculus(string userName, string password)
{// my code}
The error is in http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js function and
the "Access denied" error at e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);
I have included [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] with the class as shown in http://forums.asp.net/p/1570168/3935094.aspx and not able to fix the prob. Can any one please help me regarding this.
Thank you
AJAX calls are bound to the same origin policy meaning that you cannot invoke a web service which is situated on a different domain. The browser will simply drop the request. One possible solution would be to write a server side script on the same domain which will serve as bridge to the actual web service and then call this script.
JSONP is a possible way to workaround the "same origin policy" (aka cross-site-scripting or XSS) limitations. It comes with its own set of challenges (for example, it works only with GET-mode requests), so it's certainly not a panacea. But it's probably worth your time to give it a look. There's a decent number of stackoverflow postings about it, which should help you get started.

Getting "401 Unauthorized" error consistently with jquery call to webmethod

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

Resources