使用 ajax 请求处理 ASP.Net MVC 2 中的请求重定向

发布于 2024-12-26 12:51:09 字数 266 浏览 2 评论 0原文

我开发了一个 ASP.NET MVC2 应用程序,并在其中实现了登录功能。

我还有其他有 ajax 调用的视图。有时,我发现 ajax 调用显示登录页面。

为了摆脱这个问题,我尝试模拟这种情况,但我从应用程序获得的响应代码是 200 ,这是

我正在使用的 OK ASP.Net MVC2。为什么我得到 200,实际上我应该从当前视图获取 302 服务器重定向以进行登录页面重定向。

指导我处理这种情况。

I have developed an ASP.NET MVC2 application and in that i have a login feature implemented.

I have other views that have ajax calls. At times, i find the ajax calls displaying the login page.

In an attempt to get rid of this problem, i have tried to simulate the situation, but the response code that i get from my application was 200 which is OK

I am using ASP.Net MVC2. Why am i getting 200, where i should be actually getting a 302 server redirect for login page redirection from my current view.

Guide me to handle this situation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅浅 2025-01-02 12:51:09

为什么我得到的是 200,而我实际上应该得到的是 302 服务器
用于从我当前视图重定向登录页面。

这是因为 jQuery 遵循重定向,最终会得到 200 和登录页面。我会推荐您 下面的文章演示了一种非常优雅的方法来配置 ASP.NET 为未经身份验证的请求发送 401 状态代码,假设此请求是使用AJAX 调用。那么你的客户端代码将如下所示:

$.ajax({
    url: '/foo',
    type: 'POST',
    data: { foo: 'bar' },
    statusCode: {
        200: function (data) {
            alert('200: Authenticated');
            // Do whatever you was intending to do
            // in case of success
        },
        401: function (data) {
            alert('401: Unauthenticated');
            // Handle the 401 error here. You can redirect to 
            // the login page using window.location.href
        }
    }
});

Why am i getting 200, where i should be actually getting a 302 server
redirect for login page redirection from my current view.

It's because jQuery follows the redirect and you end up with 200 and the login page. I would recommend you the following article which illustrates a very elegant way to configure ASP.NET to send 401 status code for unauthenticated requests assuming this request was made using an AJAX call. Then your client code will look like this:

$.ajax({
    url: '/foo',
    type: 'POST',
    data: { foo: 'bar' },
    statusCode: {
        200: function (data) {
            alert('200: Authenticated');
            // Do whatever you was intending to do
            // in case of success
        },
        401: function (data) {
            alert('401: Unauthenticated');
            // Handle the 401 error here. You can redirect to 
            // the login page using window.location.href
        }
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文