While working on my asp.net mvc application i came across the scenario wherein i could not handle the session expiry. I was using windows authentication and hence i could not redirect automatically to the login page on session expiry as it happens in forms authentication. If you have worked with MVC you would also find that redirecting is not as straight forward as response.redirect in normal webforms applications. Redirection does not work if there was an intercal AJAX call or partial postback.
To overcome the problem of session expiry in case of internal AJAX calls or partial postback i devised the following javascript solution.
This is a javascript function which calls a controller method. The controller method checks if the session exists and returns a flag accordingly
function CheckSession(url, urlR) {
var html = $.ajax(
{
type: "POST",
url: url,
dataType: 'html',
async: false,
data: {
},
success:
function(result) {
},
error: function(req, status, error) {
window.alert("There was an unexpected error while checking the existence of session. Kindly contact the help desk.");
}
}).responseText;
var status = true;
var resultFromController = html.split(',');
if (resultFromController[0] == 'False') {
alert('The session is expired. You will be now redirected to the Home Page.');
window.location = urlR;
status = false;
}
else if (resultFromController[0] == 'True') {
status = true;
}
return status;
};
The javascript function is called like this
var url = "<%= Url.Action("CheckSession", "Request") %>";
var urlR = "<%= Url.Action("Index", "Home") %>";
var session = CheckSession(url, urlR);
This is the Controller function that checks if the session exists
public ActionResult CheckSession()
{
ContentResult contentResult = new ContentResult();
if (Session[StringConstants.SAPSystems] == null)
{
contentResult.Content = StringConstants.False + StringConstants.Comma + "Session does not exists";
}
else
{
contentResult.Content = StringConstants.True + StringConstants.Comma + "Session exists";
}
return contentResult;
}
No comments:
Post a Comment