Detailed. NET MVC session Failure Problem _ practical skills

Source: Internet
Author: User
Tags httpcontext

A recent study on the session failure in the. NET MVC project, the following small series to share the research process, we can refer to the next.

Recently resolved the session expiration problem based on the. NET MVC project, this conversation with you.

1. Problem analysis

In. NET MVC, session invalidation requires several things to consider:

• Authorization-based action, using non-AJAX requests;

• Authorization-based action, using JQUERYT AJAX requests;

• Authorization-based action, using the AJAX request encapsulated by the. NET MVC;

• Non-authorization action, using a AAJX request;

• Non-authorized action, using native jquery Ajax requests;

• Non-permission-certified action, using the AJAX request encapsulated by the. NET MVC;

The authorizeattribute can be intercepted and processed in the Handleunauthorizedrequest method after the Action,session failure based on the authorization. No permission-authenticated action needs to be in the custom filter, Determines and processes the difference between a new session and a requested session.

2. Non-AJAX requests based on permission authentication

Authorize filter takes precedence over other feature filters, so it inherits Authorizeattribue and processes session requests in handleunauthorizedrequest.

public class Authorizeofhandleunauthorizeattribute:authorizeattribute
{
protected override void Handleunauthorizedrequest (AuthorizationContext filtercontext)
{
//session failed redirect to login page
Filtercontext.result =
New Redirecttorouteresult (New
routevaluedictionary (new {Controller = "Login", Action = "Login"}));
}

3. The AJAX request based on the Authority authentication

The Ajax-requested action has two return results in the system: Jsonresult and Partialviewresult.

Jsonresult Theoretically, the client can judge by adding the session extended attribute to the returned result. However, given that the project is complete, it is a bit cumbersome to increase the logic of judgment on all AJAX requests.

The server-side code handles AJAX requests:

protected override void Handleunauthorizedrequest (AuthorizationContext filtercontext)
{
// Ajax request session Overtime processing
if (FilterContext.HttpContext.Request.IsAjaxRequest ())
{
FilterContext.HttpContext.Response.AppendHeader ("Sessionstatus", "timeout");
FilterContext.HttpContext.Response.End ();
return;
}
Filtercontext.result =
New Redirecttorouteresult (New
routevaluedictionary (new {Controller = "Login") Action = "Login"});
}

Client code (this is not appropriate for action that returns a result of Partialviewresult):

Onsuccess:function (XHR, status) {
//Get response headers, sessionstatus,
var sessionstatus = Xhr.getresponseheader (" Sessionstatus ");
if (Sessionstatus = = "Timeout") {
window.location = "/login/login";
}
}

The existence of the partialviewresult situation directly negates the above assumption. Most of the Ajax requests in the project are based on the. NET MVC package, which directly updates the specified div.

In order not to make a lot of changes and uniformly handle AJAX requests for two of return results, another method is found

Jquery.ajaxsetup ()

This function is used to change the default setting options for AJAX requests in jquery. All AJAX requests that are subsequently executed, and if the corresponding option parameters are not set, the changed default settings are used.

So our client code can be handled in such a unified way:

Parse Ajax Request Session timeout problem
$.ajaxsetup ({
complete:function (XMLHttpRequest, textstatus) {
var sessionstatus = Xmlhttprequest.getresponseheader ("Sessionstatus");
if (Sessionstatus = = "Timeout") {
window.location = "/login/login";
}}
);

I thought I was going to be all right here, the result was accidentally found a problem, based on the. NET MVC jquery.unobtrusive-ajax encapsulation of the AJAX request call, did not achieve the effect of blocking processing. After repeated debugging fruitless, I finally noticed the above passage

Jquery.ajaxsetup () This function is used to change the default setting options for AJAX requests in jquery. All AJAX requests that are subsequently executed, and if the corresponding option parameters are not set, the changed default settings are used.

Here to say more understand, that is certainly jquery.unobtrusive-ajax package when the ghost, opened the source a look at it so:

 $.extend (options, {type:element.getAttribute ("Data-ajax-method") | | undefined, URL: Element.getattribute ("Data-ajax-url") | | Undefined, cache:!!
Element.getattribute ("Data-ajax-cache"), Beforesend:function (XHR) {var result; Asynconbeforesend (xhr, method);
result = GetFunction (Element.getattribute ("Data-ajax-begin"), ["XHR"]). Apply (element, arguments);
if (result!== false) {loading.show (duration); }, Complete:function (xhr,status) {loading.hide (duration); GetFunction (Element.getattribute ("Data-ajax-complete"), ["XHR", "status"]).
Apply (element, arguments); }, Success:function (data, status, XHR) {asynconsuccess (element, data, Xhr.getresponseheader ("Content-type") | |
"Text/html");
GetFunction (Element.getattribute ("data-ajax-success"), ["Data", "status", "XHR"]). Apply (element, arguments); }, Error:function () {getfunction (Element.getattribute ("Data-ajax-failure"), ["Xhr", "status", "Error"]). Apply (
element, arguments); }
});

We saw Jquery.unobtrusive-ajax registering the Ajax-requested Compelete event, so the default handler we wrote was overwritten. Really did not think of any good method, had to change the source code of the Jquery.unobtrusive-ajax:

Complete:function (xhr,status) {
loading.hide (duration);
Parse Ajax Request Session timeout problem
var sessionstatus = Xhr.getresponseheader ("Sessionstatus");
if (Sessionstatus = = "Timeout") {
window.location = "/login/login";
}
GetFunction (Element.getattribute ("Data-ajax-complete"), ["Xhr", "status"]). Apply (element, arguments);

At this point, based on the authentication of AJAX request session failure problem is basically resolved, there are two defects:

• Modified the source code of the Jquery.unobtrusive-ajax, always feel uneasy;

• Any AJAX request that registers a Compelete event needs to handle the session issue itself.

4. Action with no permission task

No permission authentication action session invalidation problem, the processing code is as follows:

if (filterContext.HttpContext.Session!= null)
{
if (filterContext.HttpContext.Session.IsNewSession)
{
var Sessioncookie = filtercontext.httpcontext.request.headers["Cookie"];
if (Sessioncookie!= null&&sessioncookie.indexof ("Asp_net_sessionid", StringComparison.OrdinalIgnoreCase) >=0)
{
Filtercontext.result =
new Redirecttorouteresult (New
routevaluedictionary (new { Controller = "Login", Action = "Login"});}

Non-authorization of the action Ajax can be modeled on the authority of the processing method to deal with, here is no longer sticky code. Personal feeling, no authorization of the action request, most can not consider session failure, because most of these action does not get information from the session, just do public information inquiries.

5. Legacy issues

This problem is basically resolved, but the process encountered a puzzling problem, the next note:

I was originally in the configuration file to the expiration time set to simulate session failure, the results found that the existing framework of the project is always inexplicable strange in the first business after login please request the session extended time to 60 minutes, not find why. Later only by opening the two tab page in the same browser, after logging on to the system, the method is simulated on a tab page.

The above is described in the small series of the. NET MVC session failure problem, I hope to help you, if you have any questions please give me a message, small set will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.