How do I persist session values in ASP.NET? - asp.net

I'm implementing IHttpHandler and IRequiresSessionState and I'm using context.Session but after I set up a value in Session, it's lost in the next request. What can I do to persist the values ?
$.ajax({
url: "/test.test",
type: "POST",
data: "{'type':'GetStep'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {...}
});
The second call is similar to this, but the values that get set when I call this function are also lost on the next request.
public void ProcessRequest (HttpContext context)
{
context.Session ["Game"] = new Game (); // next time it is null
}
How do I persist values in Session state in ASP.NET ?

Do you have session state defined in your web.config? Something like this
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"/>

Related

SVC Web service consuming from code behind but not from javascript

I want to call web service in project (but in same solution) from myClient project.
I have added service reference in myClient project.
When I call scf from code behind it, works but when I try to call it from JavaScript using JSON, I am unable to do so. Guys pls help.
"http://someurl.com/MyWebService.svc/DoWork/" is path of my Service
abovive url someurl is url of localhost
This code is from a.aspx of client application of JSON,
$.ajax(
{
type: 'GET',
url: 'http://someurl.com/MyWebService.svc/DoWork/',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
alert(jqXHR.responseText);
},
success: function (data) {
alert(data);
}
});
From Code behind
string postData = "http://someurl.com/MyWebService.svc/DoWork/";
int timeout = 10;
//string dwml = string.Empty;
//MyServiceReference.MyWebServiceClient ms = new MyServiceReference.MyWebServiceClient();
//dwml = ms.DoWork();
//System.Net.WebClient webClient = new System.Net.WebClient();
//dwml = webClient.DownloadString(serviceURL);
//Response.Write(dwml);
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(postData);
// Set the Method property of the request to POST.
webRequest.Headers.Clear();
webRequest.AllowAutoRedirect = true;
webRequest.Timeout = 1000 * timeout;
webRequest.PreAuthenticate = true;
webRequest.ContentType = "application / x - www - form - urlencoded";
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
webRequest.Timeout = 150000;
// Create POST data and convert it to a byte array.
WebResponse webResponse = null;
StreamReader objSR;
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
Stream objStream;
string sResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();
objStream = webResponse.GetResponseStream();
objSR = new StreamReader(objStream, encode, true);
//<<sResponse doesn't contain Unicode char values>>
sResponse = objSR.ReadToEnd();
Response.Write(sResponse); // OR Response.write(HttpUtility.HtmlEncode(sResponse))
Guys this immediate second question (both asked by me only) which only myself has answered or commented. I got ans 4 this from stack overflows old question
Basic example of using .ajax() with JSONP?
Issue was with cross domain web-service call is not allowed through AJAX.
I came across new concept of JSONP, wow feeling great!
But I was expecting quick reply from Stack overflows other members.
I will not be able to rescue myself every time friends!
calling WCF service from RESTclient in different solution without JSONP:
Here I came up with another working solution for, calling WCF service from RESTclient in different solution without using JSONP i.e. Enabling CORS of service (Cross Origin Resource Sharing) policy.
We all must have tried:
Adding Header Access-Control-Allow-Origin in web-config file of Service Project,
Code in web-config :
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
but anyhow, that didn't worked out for me!
So, there is another way to achieve the same, is to Create a Global.asax in Service Project and Add this code to the Global.asax.cs:
Code in Global.asax.cs :
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
And you can continue with your regular AJAX call from RESTclient solution to WCF service:
Sample AJAX :
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:51058/Service1.svc/GetData",
dataType: 'json',
success: function (data) {
//do success part here
alert(data);
},
error: function (e) {
alert(e.message);
}
});
});
The best part is, no need to do any modifications in RESTclient project solution.
here I have tried so far
SVC code file service1.svc.cs :
using System;
namespace TestConnection
{
public class Service1 : IService1
{
public string GetData()
{
return string.Format("You entered: {0}", "Success");
}
}
}
JavaScript function:
<script type="text/javascript">
$(document).ready(function () {
var text;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'Service1.svc/GetData', /*you .svc address : 'http://someurl.com/MyWebService.svc/DoWork/'*/
dataType: "json",
async: false,
success: function (a) {
var response = $.parseJSON(a);
text = response.Table[0];
alert(text);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Failure');
}
});
});
</script>
All above code you might have tried, some important note to get this worked is:
1. as WCF .svc works on Representational State Transfer (REST), you have to explicitly mention data get request in service1.svc Markup file,
[OperationContract]
[WebGet()]
//You can use below attributes to make necessary modifications
//RequestFormat = WebMessageFormat.Json,
//ResponseFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Bare,
//UriTemplate= "GetData"
//)]
string GetData();
To use WebGet,you will need to add library System.ServiceModel.Web to your service Project.
And if you have issues with basic settings then,
Web.Config:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMathService" />
</basicHttpBinding>
</bindings>
</system.serviceModel>
NOTE: This will not work for cross domain, if you want that, its answered Here.

how to use jQuery ajax with asp.net user controls?

I want to use ajax with asp.net user control,
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: "{id:'" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
});
.cs code
[WebMethod]
public static string InsertTCSection(string id)
{
string result = "deneme";
return result;
}
You cannot call a method kept inside a usercontrol through jquery.
because .ascx controls don't represent real url.
They are meant to be embedded in some ASP.NET page, hence they don't exist at runtime.
what you might do is, to create a separate service and place your method there.
like webservices.
see this, this and many others
i am using generic Handler to solve this problem.
Try:
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: JSON2.stringify({ id: id}, //Your 2nd id is passing value but i dont know where its come from
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
}
)};
and in cs:
[WebMethod]
public static string InsertTCSection(string id)
{
string result="deneme";
return result;
}
I think you might be missing this attribute
[System.Web.Script.Services.ScriptService]
Before you service class as
[System.Web.Script.Services.ScriptService]
public class TCSection: System.Web.Services.WebService
{
[WebMethod]
public static string InsertTCSection(string id)
{
}
}
Or there may be one other reason that path of the webservice is not right.

Send AJAX request to .aspx page and return JSON

I know that it is possible to send an AJAX request to an .asmx page. And I also know that an .asmx page handles an AJAX request via a web method.
Is it also possible to send an AJAX request to an .aspx page? If so, does an .aspx page also handle an AJAX request via a web method? Note that I would like to return a JSON response from the .aspx page. Is this possible?
You can define web methods in the code-behind of your .aspx page and then call them:
[WebMethod]
public static string doSomething(int id)
{
...
return "hello";
}
And then, to call a web method in your jQuery code:
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
Here is a good link to get started.
if i understood question correctly, Aspx is same as HTML. It will be rendered as HTML. but only difference is Server Side and Controls retaining the states with state mechanism.
so you can do jquery $.ajax() function.
$.ajax({
url: UrlToGetData,
dataType:'json',
success:function(data){
//do some thing with data.
}
});
or if you want to write out json value to the response, then use Response.ContentType
first use any Javascript serializer(JSON.NET) , then set the contentType like this.
Response.ContentType="application/json";
$.ajax({
url: "(aspx page name/method to be called from the aspx.cs page)",
type: "POST",
dataType: "json",
data: $.toJSON(jsonData),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
//TO DO after success
}
});
Try the above code

Generating new SessionId in ASP.NET

On login I want to generate a new SessionId. I have found one solution that works, but it requires some pretty hackish things and requires the app have Full Trust securityPolicy setting.
Is there any other way to achieve this?
Looks like this works:
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
By clearing out that cookie, a new session with a new session ID will be created at the server.
(Reference: Microsoft Support)
EDIT: Here's an example using AJAX (with jQuery) to call the server code without a page refresh - it calls twice, once to remove the first session, and once to generate a new one. There may be a better way, but this does work.
function newSession() {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/ClearSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/NewSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("Success!"); },
error: function (x, y, z) {
console.log("Failure!");
}
});
},
error: function (x, y, z) {
console.log("Failure!");
}
});
}
And on the code-behind (for WebForms - you could also do this with an MVC controller):
[WebMethod]
public static void ClearSession()
{
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
[WebMethod]
public static void NewSession()
{
HttpContext.Current.Session["x"] = 123;
}
I'm currently considering a configuration-based solution, rather than a code-based one. I would configure either the web server or load balancer to strip away request and response headers containing cookies for just the login page. Remove the "cookie" headers for request headers and "set-cookie" for response headers.
Every request (GET or POST) to the login page will contain no cookie information, thus forcing ASP.NET to create a new session and (more importantly) a new session id.
It's less efficient than forcing a new session creation on login, but the technique could be useful in cases where you cannot modify the code.

Authenticate windows user using jquery

MyMasterPage.master
<head runat="server">
<script type="text/javascript">
$(document).ready(function() {
var userName = '<%# System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString() %>';
alert(userName);
$.ajax({ type: "POST",
url: "DemoWebService.asmx/GetFulName",
contentType: "application/json; charset=utf-8",
dataType: "xml",
dataType: "json",
data: "{'networkId':'" + userName + "'}",
processData: false,
error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
success: function(xml) { ajaxFinish(xml); }
});
});
</script>
</head>
Even though the userName variable is blank, I get the logged in user from my WebMethod:
[WebMethod]
public string GetFulName(string networkId)
{
//return networkId + " Full Name";
return networkId + " From Server: " + System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString();
}
Since I am checking on the master page, what is the best practice to store the authentication result so that I do not have to check on everypage. Prior to using jquery I was storing in Session.
Thanks
web.config
<authentication mode="Windows"/>
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
You could store the result in a cookie, and then check that cookie on subsequent pages to get the logged in user's name. You would want to make sure and delete the cookie if the user logged out or their authenticated session expired.
There is a plugin available for jQuery to support reading/writing/deleting cookies.

Resources