简体   繁体   English

如何根据ASP.NET C#framework 4中的登录名有条件地重定向

[英]How to conditionally redirect depending on login name in ASP.NET C# framework 4

I'm using Visual Studio 2010 ASP.NET with C# on the back framework 4 我在后台框架4上使用带有C#的Visual Studio 2010 ASP.NET

It comes with user register/login/logout mechanism. 它带有用户注册/登录/注销机制。

on load of the default.aspx page I would like to redirect the users: user1 and user2 to default2.aspx and the rest of the users to default3.asp 在加载default.aspx页面时,我想将用户:user1和user2重定向到default2.aspx,其余用户重定向到default3.asp

I would not like to use cookies, but using a session is acceptable. 我不想使用cookie,但使用会话是可以接受的。

something like: 就像是:

if (username == "user1" || username == "user2")  
{
Response.Redirect("defualt2.aspx"); 
} 
else 
{
Response.Redirect("default3.aspx"); 
}
void Page_Load(object sender, EventArgs e)
{
    switch (User.Identity.Name)
    {
        case "user2":
        case "user1":
            Response.Redirect("defualt2.aspx");
            break;
        default:
            Response.Redirect("default3.aspx");
            break;
    }
 }

However you might want to use Server.Transfer instead of Response.Redirect, if you don't want the address to change in the address bar. 但是,如果您不希望地址栏中的地址发生更改,则可能需要使用Server.Transfer而不是Response.Redirect。

来自System.Web User.Identity.Name

if (Page.User.Identity.Name == "user1" || Page.User.Identity.Name == "user2")  
{
    Response.Redirect("defualt2.aspx"); 
} 
else 
{
    Response.Redirect("default3.aspx"); 
}

That should do it as long as you're within an aspx code behind. 只要你在aspx代码中,就应该这样做。

Wow! 哇! There are tons of ways to do this. 有很多方法可以做到这一点。 When the user logs in you could set a session variable identifying the user and then use your code above but instead check for username == Session["user1"].ToString() but that code is not recommended because now you are locking yourself into hardcoding the username into the code. 当用户登录时,您可以设置一个标识用户的会话变量,然后使用上面的代码,而是检查用户名== Session [“user1”]。ToString()但不建议使用该代码,因为现在您已锁定自己将用户名硬编码到代码中。 Next would be to put the username into the web.config so it could be changed easily but again, not acceptable. 接下来将用户名放入web.config中,这样可以轻松更改,但不能接受。

It sounds like you are probably doing this for security reasons. 听起来你出于安全考虑可能会这样做。 If that is the case, you should look into the Role Provider that is already part of the Framework. 如果是这种情况,您应该查看已经是Framework的一部分的角色提供程序。 This provides you with a mechanism to place users in specific roles and then based on that role allow or disallow users on certain pages based on a decorator above the class. 这为您提供了一种机制,可以将用户置于特定角色,然后根据该角色允许或禁止某些页面上的用户基于类上方的装饰器。

I would not use the code you have posted in any circumstance. 我不会在任何情况下使用您发布的代码。 It is not good practice to hard-code usernames into code. 将用户名硬编码到代码中并不是一种好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM