且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何隐藏登录用户的登录字段

更新时间:2023-11-30 18:56:40

内置的系统可以帮助您进行登录.出于多种原因,不应使用会话变量.

There are built in systems to help you with the login. Session variables shouldn't be used for several reasons.

要设置登录名,您可以在控制器内部使用以下功能:

To set the login, you can use the following function inside your controller:

FormsAuthentication.SetAuthCookie(UserName, remember);

类似地,您可以使用 FormsAuthentication.SignOut()登出.

Similarly you can use FormsAuthentication.SignOut() for logging out.

现在在剃须刀中或任何控制器中,您可以检查 User.Identity.IsAuthenticated 以验证用户是否已登录.

Now within your razor or in any controller you can check for User.Identity.IsAuthenticated to verify if the user is logged in.

要使用此功能,还需要确保在web.config下的< system.web> 下具有以下内容:

For this functionality to work, you also need to make sure you have the following under your web.config, under your <system.web>:

<authentication mode="Forms">

</authentication>

此外,如果您想利用此登录功能,可以将登录表单添加到与首页不同的单独的cshtml页面中.可以说此页面位于 Home/Login 的位置.现在,您可以在web.config中修改上述代码,如下所示

Further more if you would like to take advantage of this login feature, you can add your login form into a separate cshtml page different from your home page. Lets say this page is in the location Home/Login. Now you can modify the above code within web.config as follows

<authentication mode="Forms">
    <forms loginUrl="~/Home/Login" timeout="2880" />
</authentication>

这将分配您的默认登录页面.现在,如果仅在登录时需要访问任何URL,如果用户未登录,它将自动重定向到该位置.要指定某个操作需要身份验证,请在该操作之前使用 [Authorize] 或整个控制器(如果需要整个控制器的授权).您的操作将如下所示:

This assigns your default login page. Now if any URL needs to only be accessed on login, it would automatically redirect to this location if the user is not logged in. To specify that an action needs authentication, use [Authorize] before the action or the entire controller if you need the whole controller authorized. Your action will look something like this:

[Authorize]
public ActionResult Index(){
    return View()
}

最后,您的示例 HomeController 看起来可能像这样:

Finally your sample HomeController can look something like this:

public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Login()
    {
        return View();  // for the login form
    }

    [HttpPost]
    public void Login(string UserName, .... <other fields>)
    {
        // validate your login first here
        FormsAuthentication.SetAuthCookie(UserName, true);
    }

}