调用AuthorizationRequired类中的AllowAnonymous方法给我302错误

本文关键字:错误 方法 AllowAnonymous AuthorizationRequired 调用 | 更新日期: 2023-09-27 18:18:08

我试图在我的AccountController中调用一个方法,这是一个AuthorizationRequired类。方法调用时,用户尚未获得授权。所以我写了这样的方法:

        [HttpPost]
    [AllowAnonymous]
    public ActionResult Accept()
    {
        string memberno = TempData["memberno"] as string;
        _accountRepository.AcceptTerms(memberno);
        Account acc = _accountRepository.GetAccount(memberno);
        LoginViewModel loginView = new LoginViewModel
        {
            MemberNo = acc.AccountNo,
            Password = acc.Password,
            ForgotPassword = false,
            RememberMe = false
        };
        return Login(loginView,"");
    }

调用它的方法是$.ajax方法:

    function acceptTermses() {
    $.ajax({
        url: '@Url.Action("Accept", "Account")',
        type: "POST",
        success: function (da) {
            alert("did it");
        }, error: function (w) {
            alert("FAILED");
        }
    });
}

但是当我尝试调用这个方法时,我在浏览器中得到这个:

Remote Address:::1:33405
Request URL:http://localhost:33405/Account/Accept
Request Method:GET
Status Code:302 Found

Failed to load repsonse data

不是失败我的方法,而是在302 Found调用之后执行此调用:

http://localhost:33405/Account/Login?ReturnUrl=%2FAccount%2FAccept

然后它运行时显示"success",但从不调用控制器方法。

我尝试对类中的另一个方法进行相同的调用,并且工作得很好。我不知道为什么它不能运行这个方法

调用AuthorizationRequired类中的AllowAnonymous方法给我302错误

return Login(loginView,"")有问题,即重定向到Login Action,这在您的问题中是错误的。

Try This:-

[HttpPost]
[AllowAnonymous]
public ActionResult Accept()
{
    string memberno = TempData["memberno"] as string;
    _accountRepository.AcceptTerms(memberno);
    Account acc = _accountRepository.GetAccount(memberno);
    LoginViewModel loginView = new LoginViewModel
    {
        MemberNo = acc.AccountNo,
        Password = acc.Password,
        ForgotPassword = false,
        RememberMe = false
    };
    return Json({ message="success" }, JsonRequestBehavior.AllowGet)
}
function acceptTermses() {
$.ajax({
    url: '@Url.Action("Accept", "Account")',
    type: 'POST',
    datatype:'JSON',
    success: function (data) {
        if(data.message=="success"){
        window.location.href="/Account/Login";
       }
    }, error: function (w) {
        alert("FAILED");
    }
});
}