本文介绍了如何在AJAX中使用自定义AuthorizeAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在朋友的帮助下,我设法从以下主题中找到了解决我的问题的方法:

With help of fellow friends I managed to find a solution for my problem from this topic: Reusable way to allow an account to be used by a single person at a time

我有一个SingleLogin类,该类继承自AuthorizeAttribute并实现了自定义AuthorizeCore方法,以实现单次登录代码的可重用性:

I have a SingleLogin class which inherits from AuthorizeAttribute and implements a custom AuthorizeCore method for the purpose of re-usability of my single-login code:

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool isAuthorized = base.AuthorizeCore(httpContext);

        if (isAuthorized)
        {
            int userId = (int)WebSecurity.CurrentUserId;
            using (var db = new UsersContext())
            {
                if ((httpContext.Session.SessionID != db.getSessionId(userId))
                    || db.getSessionId(userId) == null)
                {
                    WebSecurity.Logout();
                    isAuthorized = false;
                    httpContext.Response.Redirect("/Home/Index");
                }
            }
        }

        return isAuthorized;
    }

除了我的JsonResult动作之外,一切都正常:

Everything works fine except my JsonResult action:

    [HttpPost]
    public JsonResult MessageSave(string message)
    {
        bool messageSaved = false;
        int userId = (int)WebSecurity.CurrentUserId;
        message = HttpUtility.HtmlEncode(message);

        // Model method - adding chat log - db
        db.addChatLog(message, userId);
        messageSaved = true;

        return Json(new { messageSaved = messageSaved });
    }

此方法由Ajax POST调用触发,您可以在下面的代码示例中看到.只是基本的POST.

This method is triggered by Ajax POST call which you can see in code example below. Just basic POST.

编辑3 请检查以下图片: http://imgur.com/a/Cjael ..我猜是POST确实会触发,但不知道为什么我尝试在$ .ajax之前对其进行测试时我的警报为什么不起作用...如响应所示,我确实获得了首页/索引"页面,但我没有立即重定向到首页/索引(文本停留在textBox内,而页面仅在等待..),我必须再按一次Enter才能进行重定向..很奇怪.

EDIT 3Please check these images: http://imgur.com/a/Cjael .. Hm I guess POST does trigger, but have no idea why does my alert not work when I try to test it before $.ajax ... As you can see in response I do get Home/Index page but I am not redirected to home/index immediately(text stays inside of textBox and page just waits..), I have to push enter one more time to be redirected.. Very strange.

EDIT2 好像我注销后甚至都无法访问我的jQuery.我在.js文件中放了一些警报.

EDIT2Seems like I can't even access my jQuery even after I get logged out. I put some alerts inside of my .js file.

我有一个单独的.js文件,然后将其作为<script src="~/Scripts/custom/homeChat.js"></script>放在我的视图中.我通过HTML5数据将View的Razor值传递到我的JS文件中.

I have a separate .js file which is then put in my View as <script src="~/Scripts/custom/homeChat.js"></script> . I pass the Razor values from View into my JS file via HTML5 data-.

我的textBox元素#txtMsg触发了我的jQuery事件,因此当我注销时,它可能不再识别我的textBox元素,并且也不会触发我的jQuery事件?

My textBox element #txtMsg, triggers my jQuery event, therefore when I am logged out it probably doesn't recognize my textBox element anymore, and doesn't trigger my jQuery event?

在视图中触发.js的元素是:@Html.TextBox("txtMsg")

Element that triggers .js in view is:@Html.TextBox("txtMsg")

JS:

$("#txtMsg").keypress(function (e) {

        //when enter
        if (e.which == 13) {
            alert("ALERT DOESNT TRIGGER");

                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify({ message: input }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.messageSaved) {
                            $("#txtMsg").val("");
                        }
                        else {
                            window.location.href = urlhome;
                        }
                    }
                });
            }
        }
    });

因此,如果您什至无法参加活动,您怎么能知道出了什么问题?我有这个˙HandleUnauthorizedRequest,但是如果我理解正确的话,您必须进入jQuery事件(在我的情况下,上面的js代码中为 .keypress ),才能正常工作.

So if you can't even come into your event, how can you even know something went wrong? I have this ˙HandleUnauthorizedRequest but you are required that you can get into your jQuery event(in my case .keypress in the js code above) for this to work if I understand right.

附加说明

所以让我解释一下情况.如果我使用Firefox的用户名"john"登录,然后再次使用chrome的用户名"john"登录,那么我将在Firefox中执行下一步操作,它将注销我并将其重定向到首页/索引",因为其他人在Chrome中进行了新的登录

So let me explain the scenario. If I login with my username "john" from Firefox and again with username "john" from chrome, next action I do in Firefox, it will log me out and redirect me to Home/Index, because someone else made a new login in Chrome.

没关系.由于您不再登录,因此,如果您的操作是正常的ActionResult并返回视图,则可以正常重定向到您的主页/索引.

That is ok. Since you are not logged in anymore, you get redirected normally to your Home/Index if your action is normal ActionResult and returns view.

我的问题是,页面上还有其他一些功能,该功能使用Ajax POST,并且由于您已注销,您无法POST到该JsonResult操作,因此您甚至无法收到错误的回调,会将您重定向到首页/索引".我在JS中放了一些警报,但没有正常的警报触发器,因为无论如何我都不再被允许进入该页面.如果我希望我的onEnter文本框将我重定向到首页/索引",则必须按两次Enter键.那是所有可以做到的吗?

The problem I have is, that I have some other functionality in the page, which uses Ajax POST, and since you are logged out you can't POST to that JsonResult action therefore you can't even receive callback of error, which redirects you to Home/Index. I put some alerts into my JS, but no alert triggers which is normal, because I am not allowed on that page anymore anyway. If I want that my onEnter textbox redirects me to Home/Index I have to press enter twice. Is that all that could be done?

我对解决AJAX问题的最佳方法感兴趣.我不知道该怎么称呼,但是正如我从上一个主题中读到的那样,它被称为处理AJAX超时"?

I am interested in best approach for this AJAX problem. I don't know how I should call it, but as I read from my previous topic it is called "handling AJAX timeouts"?

非常感谢您.

推荐答案

您可以通过这种方式处理有关AJAX请求的错误

You can handle errors on AJAX request this way

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify({ message: input }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        if (data.messageSaved) {
            $("#txtMsg").val("");
        }
        else {
            window.location.href = urlhome;
        }
    },
    error: function(xhr, status, error) {
        // TODO: may be check error or status or xhr.statusCode()
        window.location.href = urlhome;
    }
});

jQuery $.ajax()文档

这篇关于如何在AJAX中使用自定义AuthorizeAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:51