【问题标题】:Redirect from Webmethod in Asp.Net从 Asp.Net 中的 Web 方法重定向
【发布时间】:2026-02-18 12:25:01
【问题描述】:

我是 Asp.Net 编程新手,刚刚开始了一个 Web 项目。 我正在使用 JSON 从 Aspx 页面调用 WebMethod,如下所示:

 <script type="text/javascript">

    function getLogin() {
        var userName = document.getElementById('TextBox1').value;
        $.ajax({
            type: "POST",
            url: "Services/LogService.asmx/authenticateLogin",
            data: "{'userName':'" +userName.toString()+ "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
            alert(response.d)
            },
            error: function (xhr, status, error) {
                // alert(textStatus);
                DisplayError(xhr);
            }

        });
    }


function DisplayError(xhr) {
 var msg = JSON.parse(xhr.responseText);
 alert(msg.Message);  }
</script>

和WebMethod:

[WebMethod]
    public string authenticateLogin(string userName)
    {
        LoginBO loginBO = new LoginBO();
        loginBO.userName = userName.ToString().Trim();
        string result = "";
        try
        {
            LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
            result = loginDao.selectUser(loginBO);
        }
        catch (DBConnectionException)
        {
            //result = "DB Conenction";
            throw new Exception("DB Connection is Down");
        }

        catch (InvalidLoginException)
        {
            //HttpResponse res = new HttpResponse();
            //HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
            throw new InvalidLoginException("Login Is Invalid");
        }
        catch (Exception)
        {
            throw new Exception("Uanble to Fetch ");
        }
        int ctx = Context.Response.StatusCode;
        return result;
    }

验证成功后,我想将用户重定向到另一个 aspx 页面。

最佳做法是什么?

谢谢 塞缪尔

【问题讨论】:

    标签: asp.net web-services web-applications


    【解决方案1】:

    将重定向添加到 getLogin() 函数的成功部分:

    success: 
      function (response) {
        alert(response.d);
        windows.location.href = "http://url.for.redirect";
      }
    

    (或使用some other method 在jQuery/Javascript 中进行重定向)。

    【讨论】:

    • 埃利斯,用什么重定向 window.location.href 或 window.location.replace?
    • 参见this post - 它讨论了不同的选项及其优缺点。似乎更喜欢replace 方法。
    【解决方案2】:

    在你的 Ajax 方法中

    success: function(msg) {
          alert(response.d);
            window.location = "xyz.aspx";
      },
    

    【讨论】:

      【解决方案3】:
             success: function (response) {
                alert(response.d)
               window.location.href = "some.aspx";.
              }    
      

      我想它会对你有所帮助。

      【讨论】: