下面的代码的“尝试捕获”块中有问题。
在函数SetUser中,如果用户存在于数据库中,则使用getId函数返回一个ID,否则,我将收到NullReferenceException。
我在Login中的try catch块中调用此函数。我有一个问题,因为当生成异常时,我希望将用户重定向到注册页面。但是,当我尝试与不存在的用户执行代码时,我认为我有一种无限循环,因为我的页面不会停止加载。我不明白我在做什么错。需要帮助
功能登录:
public static void Login(HttpRequest Request, HttpResponse Response, string redirectUri)
{
if (Request.IsAuthenticated)
return;
if (!Request.Form.AllKeys.Contains("id_token"))
return;
string value = Request.Form.Get("id_token");
JObject id_token = JwtDecode(value);
string upn = id_token.GetValue("upn").ToString();
DateTime expiretime = GetExpireTime(id_token);
try
{
SetUser(id_token);
}
catch (Exception ex)
{
Response.Redirect("~/register.aspx");
}
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, upn, DateTime.UtcNow, expiretime, false, id_token.ToString(), FormsAuthentication.FormsCookiePath);
string encryptedcookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedcookie);
cookie.Expires = expiretime;
Response.Cookies.Add(cookie);
redirectUri = GetRedirectUrl(Request, redirectUri);
Response.Redirect(redirectUri, true);
}
功能setUser:
private static void SetUser(JObject id_token)
{
string email = id_token.GetValue("unique_name").ToString();
string name = id_token.GetValue("given_name").ToString();
DataSet ds;
List<Claim> claims = new List<Claim>()
{
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Name, GetId(email))
};
string roles= "SELECT name FROM AspNetRoles;
ds = GetDataSet(roles);
if (ds.Tables.Count > 0)
{
foreach (var row in ds.Tables(0).Rows)
claims.Add(new Claim(ClaimTypes.Role, row("name")));
}
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Cookies");
ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
HttpContext.Current.GetOwinContext().Authentication.User = principal;
Thread.CurrentPrincipal = principal;
}
function getId:
public static string getId(string email)
{
return ((new UserManager()).FindByEmail(email)).Id;
}