Handling session expiration in ASP.NET MVC when making an AJAX call by redirecting to the login page

I'm currently learning ASP.NET MVC and I'm a newbie in it, so I'm struggling to find a solution for a specific problem. If anyone has encountered this issue before, I would appreciate any advice. Thank you!

In my project, I am using ASP.NET Identity for authorization. The main issue I'm facing is how to redirect the user to the login page after the session expires. Everything works fine if the action is initiated from a controller and not through AJAX. However, when the action is triggered through an AJAX function, it crashes. I've been searching for a solution but haven't found anything that works for me yet. Currently, my code looks like this:

Startup.cs

public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Login"),
                LogoutPath = new PathString("/Home/Login"),
                ExpireTimeSpan = TimeSpan.FromMinutes(1),
               
            });
        }

Web.config

<system.web>
    <authentication mode="Forms">
    <forms loginUrl="~/Home/Login"  timeout="1" />
    </authentication>
  </system.web>

The JS function that calls the action:

function click(d) {
                //Some logic
                    $.ajax({
                        url: '@Url.Action("GetDataForNode", "Home")',
                        type: 'POST',
                        dataType: 'json',
                        cahe: false,
                        data: { uid: d.id, index: index, nodesUid: nodesUid, request },
                        success: function (results) {
                            //Some logic
                        },
                        error: function (xhr) {
                            if (xhr.status === 401) {
                                window.location.href = xhr.Data.LogOnUrl;
                                return;
                            }
                        }
                    })
            }

And in the controller, I have created:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NotAuthorized",
                        LogOnUrl = FormsAuthentication.LoginUrl
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                filterContext.HttpContext.Response.End();
                
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }

Upon execution, I encounter this https://i.stack.imgur.com/Rg52t.png

Answer №1

Make sure to include a life cycle method Application_EndRequest handler in your global.asax.cs file. This method will be triggered at the end of every request, giving you the opportunity to redirect to the appropriate action when a request is unauthorized (401).

   protected void Application_EndRequest()
        {                
            // Redirect to the login page.
            var context = new HttpContextWrapper(Context);
            if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 401)
            {
                new RedirectResult("~/Account/Login");
            }
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing the React Router component as a variable

I'm currently working on integrating React-Router into an existing React app. Is there a way to use react-router to dynamically display components based on certain conditions? var displayComponent; if(this.state.displayEventComponent){ {/* ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

How does handleChange receive the value as an input?

Greetings! Currently, I am delving into the world of React and JavaScript. I am experimenting with a Table Component demo that can be found at the following link: https://codesandbox.io/s/hier2?file=/demo.js:5301-5317 In the demo, there is a function defi ...

The concept of recursion in AngularJS directives

I developed a unique custom directive. angular.module('menu',[]) .directive('MenuDirective',function(){ return{ restrict:'E', replace:'true', scope:{ m ...

What is the purpose of using a single pipe character within a Vue.js template handlebar expression?

Here is a sample code snippet: <div> {{ name | capitalize }} </div> I have searched through the documentation for vuejs and handlebars, but couldn't find any relevant information. ...

Troubleshooting Angular and ASP.NET Core MVC: Addressing the "Uncaught SyntaxError: Unexpected token '<'" issue with index file references post deployment

My application is built using ASP.NET Core MVC and an Angular UI framework. Everything runs smoothly in the IIS Express Development Environment, but when switching to the IIS Express Production environment or deploying to an IIS host, I encounter issues wi ...

An Ajax post request will only display output if multiple echo statements are present

Utilizing ajax to handle a login form, everything within the request is functioning correctly except for one issue. The data is being sent to the file login.php. The relevant code in that file looks like this: $dealer = $stmt->fetch(PDO::FETCH_ASSOC); ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

JavaScript and the importance of using commas in arrays

I am developing a system that displays text in a textarea when a checkbox is checked and removes the text when the checkbox is unchecked. The functionality is mostly working as intended, but I am facing an issue where commas remain in the textarea after un ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

How can I ensure that the AppBar background color matches the color of the navigation bar?

Having trouble changing the background color of the <AppBar> in my project. Using the Container component to set a maximum screen size, but encountering issues when the screen exceeds this limit. The AppBar background color appears as expected while ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

What is the best way to accurately establish a new name for the evolving scope

var tags_offset=[]; $scope.getRelations = function(id, ref, subRef=0){ tags_offset[ref+'-'+subRef]=0; $http.get( CONS.appHttp+ '/tags.php?ID='+id +'&ref='+ref +'&contentType='+subRe ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

What is the best way to retrieve the value of a checkbox element in React.js when submitting a form?

Whenever I try to submit a form, I encounter an issue where I am unable to retrieve the value of the checked boxes (I don't mean the check value but the actual value attribute of the HTML element). Here is an example of my element in the parent compo ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...