Handle session timeout in generic http handler - asp.net

I have an application where around 20 http generic handler are used for ajax call.
I have used IReadOnlySessionState for accessing the session in my handlers.Everything is working fine.
But when session expires my handler is returning some html as it redirects to default page and html of default page is sent back in the response.
To overcome this issue.
I have checked the session variable in the handler and if it is null the I have written
context.Response.Write("logout")
And I check in jQuery ajax weather it is logout or anything else.
$.ajax({
url: "myhandler.ashx",
contentType: "application/json; charset=utf-8",
success: function (data) { checklogout(data); $("#loading").hide(); },
error: function () { $("#loading").hide(); },
async: false
});
If it is logout then I have used location to redirect to login page.
I am using form-authentication to authenticate user.
Is there any better approach for checking and redirecting to login page using jquery-ajax call.

You have your handlers in a directory that automatically control by the authentication of asp.net.
What I should do is to not let automatically control by the asp.net authentication by setup that on web.config so the call to the handler will done ether the user is logged in ether not, and inside the handlers I will check for that, if the user that call that handler have the session and the authentication.
Then in the case that the user did not have the authentication to read that handler I return a simple flag to my ajax call, then recognize and make redirect, eg as:
$.ajax({
url: "myhandler.ashx",
contentType: "application/json; charset=utf-8",
success: function (data)
{
if(data.redirectToLogin == true)
{
window.location = "/login.aspx"
}
else
{
// do the rest job
}
},
error: function ()
{
$("#loading").hide();
}
});

Related

How can i retrive session from asp.net using Jquery

How can I retrieve session variable stored in a.aspx using Jquery? I have username stored in the session, I need to retrieve the session to display the username in the menu bar.
A person login through A.aspx and his details has to be displayed(from database) in B.aspx
One way to handle this would be to create a Web Method or similar within your current page so that you could access the updated value of the Session via an AJAX call :
[WebMethod]
public static string GetSessionValue(string key)
{
return Session[key];
}
Then you could make a POST call via AJAX to request the specific key that you needed (or you could ignore any parameters and simply hard-code the key that you wanted to pull within the method itself) :
public static string GetSessionDisplayName()
{
// Use the name of your Session key here to retrieve your info
return Session["DisplayName"];
}
And then you could use the following jQuery code to pull it with a parameter :
$.ajax({
type: "POST",
url: "YourPage.aspx/GetSessionValue",
data: '{ key: "your-session-key" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// data will hold your Session value, use it here
alert(data);
}
});
Or without one :
$.post('YourPage.aspx/GetSessionDisplayName',function(data){
// data will hold your Session value, use it here
alert(data);
});

Ajax not executing asynchronously

I have this piece of code
function getMesssages(id,c) {
function waitForServerCall(id,c) {
$.get(href("~/polling/" + id), function (response) {
var r = c(response);
if (r) {
return false;
}
waitForServerCall(id);
});
}
waitForServerCall(id,c);
$.post(href("~/batch/export/?batches=3344&pollid=" + id), function (response) {
c(response);
cancelCall = true;
});
}
The $.get inside the waitForServerCall method only get execute when the $.post recive the server response. Why?
This is the ajaxSettings:
accepts: Object
async: true
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
contents: Object
converters: Object
flatOptions: Object
global: true
isLocal: false
jsonp: "callback"
jsonpCallback: ()
processData: true
responseFields: Object
type: "GET"
url: "http://localhost:59161/"
xhr: In()
__proto__: Object
Update.
What i am doing is long polling, the post request is a long running process so i need to know some events that the server will trigger, the waitForServerCall method notify the client about the events that occured. But since the $.get method execute once the $.post response is recive, the notification process don't work.
Update 1:
Im using .NET 4.0 and Jquery 1.9.1.
Yes, the $.get request gets execute first but not response is recive until the $.post get the response. Once the $.post get the response, $.get execute correctly. But I'm expecting the $.get to get the server response even if the $.post has not get any response yet.
So here is the answer of why.
All the credits goes to the author of this article:
http://josefottosson.se/c-sharp-mvc-concurrent-ajax-calls-blocks-server/

Securing Webservice called by ajax

i have built website with asp.net webservice where the user can register and login and make ads but the main issue that the webservice is not secured cause i can call it and pass parameters to it in the basic console of the google chrome i can execute webmethod and add user with any role i like without any credentials the code is
$.ajax(
{
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/anywebservice.asmx/AddUser',
data: JSON.stringify({
FullName: $('#txtFullName').val(),
BirthDate: "1/1/1900",
GenderId: $("input:radio[name='rblGender']:checked").val(),
CountryId: $("#ddlCountries").val(),
Email: $('#txtEmail').val(),
Mobile: $('#txtMobile').val(),
RoleName: "Users",
LoginName: $('#txtUserName').val(),
Password: $('#txtPassword').val(),
IsApproved: "true"
}),
beforeSend: function () {
//$('.tableContent').block({ message: null });
//$('.tableContent').spin(opts);
},
complete: function () {
//$('.tableContent').unblock();
//$('.tableContent').spin(false);
},
success: function (data) {
if (data.d < 0) {
CustomAlert(data.d);
}
else {
CustomAlert(window.lang.translate("You have sucssesfully registered"));
}
}
});
of course i know that i can create separated webmethod that does not take role name as parameter but this method is just example i have many methods that i am using for the clients but i need them to be secured not like this or i should separate the admin webservice from the client webservice and if so how can i secure both
Require authentication/authorization on any AJAX request you want to secure.
In your example, add 2 parameters: the LoginName and Password of the user submitting the request. Then perform authentication/authorization on the sever to ensure the user has rights to add a new user. Return a 403 response if they are not authorized.

Jquery Ajax error for asp.net page

I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.
EX:
Actual webpage: www.mysite.com/about // which has about folder and a user control inside it
there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.
here is Jquery part.
$(document).ready(function () {
$('.info a').click(function () {
$.ajax({
type: 'POST',
url: '/about/showServer', //which url to put here
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("result.d");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
});
});
});
C#
[WebMethod] // this method is in the user control
public static string showServer()
{
return "Hello from server";
}
How to call this method from client using $.ajax
appreciate your time and help.
EDITS
I have this structure for my website
mysite.com/about
/about/defualt.aspx --> which loads the user controls
user controls resides in
mysite.com/ConLib/Custom/about.ascx/showServer
So i set it to like this
url: '/ConLib/Custom/about.ascx/showServer',
BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..
Your ajax success method should be this:
alert(result.d);
Instead of this:
success: function (result) {
alert("result.d");
}
and url should be:
url: "Default.ascx/showServer", // UserControlPage/MethodName
you need to decorate your web method
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
public static string showServer()
{
return "Hello from server";
}
If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
The url: param should be in the form of '/MyPage.aspx/showServer'

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.

Resources