如何通过WebMethod进行身份验证

时间:2013-05-21 11:20:53

标签: asp.net authentication membership

我在Json格式中通​​过Ajax传递了userName并传递给.aspx页面中的webmethod, 现在我想要验证用户并将用户重定向到同一页面并使用LogedIn State更新LoginView;

我该怎么办? 这是我的WebMethod

[WebMethod]
    // [ [System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=false)]
    public static void login(object myData)
    {

        JavaScriptSerializer js = new JavaScriptSerializer();
        List<nameVal> myfrm = js.Deserialize<List<nameVal>>(myData.ToString());
      //  MembershipUser u = Membership.GetUser(myfrm.SingleOrDefault(rs=>rs.name=="userName").value);

        if (  Membership.ValidateUser(myfrm[0].value,myfrm[1].value))
        {
            FormsAuthentication.Authenticate(myfrm[0].value, myfrm[1].value);
            //FormsAuthentication.RedirectFromLoginPage(myfrm[0].value, false);

            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, myfrm[0].value, DateTime.Now,
            DateTime.Now.AddMinutes(30), true, "my custom data");
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

            ck.Path = FormsAuthentication.FormsCookiePath; 
            //  ******* now i must somthing like this: -->  Response.Cookies.Add(ck);
            // but im in static method don't have respons request objects
            // i want respons in json form and proccess the json


           // return "Success";
        }
        else
        {
            //return "Faild";
        }

    }

所以坦克

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

FormsAuthentication.SetAuthCookie(myfrm[0].value, createPersistentCookie: false);
return FormsAuthentication.GetRedirectUrl(user.Name, false);

然后在你的javascript:

var onSuccess = function (result) {
   if (result === null) {
      // login failed
      return;
   }
   window.location.href = result;
};

PageMethods.login(myData, onSuccess);

不幸的是,这仍然是一个沉默的&#34; ThreadAbortException我似乎无法摆脱,但它似乎没有造成任何问题。我认为这可能是不可避免的和良性的。

相关问题