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

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Troubleshooting: Page Unable to Import/Execute Linked JavaScript on WebStorm with Node.js Backend

I've been following W3School's jQuery tutorial, but I'm encountering some issues with importing scripts to an HTML document hosted on a Node server in WebStorm. I have properly installed and enabled the jQuery libraries under Preferences &g ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

Guide to receiving a File and Json data in a Post endpoint using .NET

I am currently utilizing the Aradalis Endpoints package for my application. I have a Post endpoint where I want to be able to accept both a file and an object in JSON format, which I then deserialize. Below is the code snippet for my endpoint: namespace ...

Tips on effectively rendering child components conditionally in React

My components currently consist of an AddBookPanel containing the AddBookForm. I am looking to implement a feature where the form is displayed upon clicking the 'AddBookButton', and hidden when the 'x' button (image within AddBookForm c ...

What is the best way to incorporate a Thymeleaf message stored in message.properties into my JavaScript file?

Is there a way to insert messages from a message.properties file into a javascript file similar to how it's done in an HTML file? For example, on my home page I have a title listed as: <h1 th:text="#{home.screen.title}"></h1> Where home ...

Is there a way for me to retrieve the data returned from a worker thread?

In my quest to understand how worker-threads function, I've come across this useful example: https://github.com/heroku-examples/node-workers-example.git REMINDER: Ensure Redis is installed and running for this example My primary challenge lies in r ...

I'm puzzled, can anyone provide clarification on the concept of xml?

Recently, Sheshank S. provided me with a solution to my question, but I failed to grasp its meaning. Can someone please explain it to me? Despite looking through various tutorials on websites and videos, none of them have been able to clarify what this cod ...

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

Error Encountered: Unexpected Identifier in Angular 7 External jQuery Plugin

Struggling to convert a jQuery template to Angular7, I'm facing an issue with loading .js files from the assets folder in the original template to make it functional. Upon starting the application with: ng serve, I encounter the following error in th ...

Using Cordova for mobile applications to play local video files

Our iOS app, developed using PhoneGap / Cordova 4.3.0, loads an external website directly utilizing <content src="http://example.com/foo" /> in the config.xml file. All functionality resides within this website, eliminating the need for local HTML or ...

What is the mechanism behind making a Promise appear synchronous when using a Proxy in JavaScript?

const handler: ProxyHandler<any> = { get: (target: Promise<any>, prop: string, receiver: any) => { return target.then((o) => { return o[prop].apply(o); }); }, }; return new Proxy(obj, handler) ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Creating well-formatted JSON from a C# class

I have a C# class called "occ" with properties like from, to, Ktype, and bool. These properties are filled using EF6.0 function that retrieves data from a stored procedure. Now, I need to create a JSON object for each record in the class with the followi ...

Using AJAX to Access PHP Variables

I am working on creating a progress bar and have the following CSS code: #result{ background:#8c8f91; margin-left: 15px; margin-right: auto; table-layout: fixed; border-collapse: collapse; z-index: -1; position:relative; width: ...

Is there a way to use jQuery to adjust the text color once it has been clicked on?

I have been struggling to change the text color upon clicking on it without any success. Within my code, there are seven labels - one for the question, four for the answer options, one for the correct answer, and the last one for the explanation. The desi ...

Setting the backEnd URL in a frontEnd React application: Best practices for integration

Hey there - I'm new to react and front-end development in general. I recently created a RESTful API using Java, and now I'm wondering what the best way is to specify the backend URL for the fetch() function within a .jsx file in react. Currently, ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

Slider - incorporating a heading onto a video with HTML styling

Is there a way to display a title on a slider when one of the slides contains a video? Here is an example code snippet: <!-- Swiper--> <div data-height="100vh" data-min-height="480px" data-slide-effect="fade" class="swiper-container swiper-s ...