protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
if (!IsPostBack)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
}
用户进入并且他已通过身份验证,但当我检查他的名字时,我得到了“” 我尝试使用jquery ajax获取用户名,然后将数据返回给ajax
更新 当名为moria的用户是logedin
时,请查看我的即时窗口(在断点处)**User.Identity**
{System.Web.Security.FormsIdentity}
[System.Web.Security.FormsIdentity]: {System.Web.Security.FormsIdentity}
AuthenticationType: "Forms"
**IsAuthenticated: true**
**Name: ""**
**Membership.GetUser()**
**null**
**Membership.GetUser("moria")**
{moria}
Comment: null
CreationDate: {23/02/2016 01:10:08}
Email: "orders.gca@gmail.com"
IsApproved: true
IsLockedOut: false
IsOnline: false
LastActivityDate: {24/02/2016 03:21:08}
LastLockoutDate: {01/01/1754 02:00:00}
LastLoginDate: {24/02/2016 03:21:08}
LastPasswordChangedDate: {23/02/2016 01:10:08}
PasswordQuestion: "1"
ProviderName: "MySqlMembershipProvider"
ProviderUserKey: {ff589472-e852-4049-8803-6d22740414ee}
UserName: "moria"
答案 0 :(得分:1)
根据ADreNaLiNe-DJ的回答并添加重定向回调用页面的功能,您可以将其添加到Global.asax文件中:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var loginUrl = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Login", "Account") ?? "";
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains(loginUrl))
{
Response.Redirect(loginUrl + "?ReturnUrl=" + Request.Url.AbsoluteUri);
}
}
希望有所帮助。
答案 1 :(得分:0)
首先,您应该在管道中更早地检查身份验证。 在Global.asax.cs中添加此代码:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains("login.aspx"))
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
}
您在一个独特的地方检查所有网页/请求的身份验证。
因此,当您在 Page_Load 中时,您一定会登录并进行身份验证。
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}