2012-02-20 94 views
6

我想在用户屏幕顶部显示一个工具栏,如果他们已经登录,他们可以访问他们的帐户等。如果他们没有登录,它会显示一个表单,允许他们登录。我不完全确定如何使用C#和Razor来执行此操作,并继续触发语法和编译错误。检查cookie是否设置

我目前的表格如下:我有一个文件,_siteLayout.cshtml。这将工具栏存储在屏幕顶部。它会根据外部数据库检查登录表单,如果它被验证,创建会为客户端提供一个cookie。我基本上想要的形式是

if(user logged in) 
    render account management page 
else{ 
    render login page 
} 

很简单,但我遇到了很多问题。以下是我的代码,目前已删除批量:

<body> 
    @using System.Text; 
    @using System.Net.Sockets; 
    @{ 
     if(Request.Cookies["mpUsername"] == null){ 
     //if user is not logged in 
      //some authentication is ran, if passed, isValid is set to true  
       if (isValid) { 
        //login is valid, set cookie 
        HttpCookie cookie = Request.Cookies.Get("mpUsername"); 
       if(cookie == null) { 
        cookie = new HttpCookie("mpUsername"); 
        cookie.Value = username; 
        cookie.Expires = DateTime.Now.AddDays(3); 
        Response.Cookies.Add(cookie); 
       } 
       } else { 
        //login invalid, prompt for pass again 
       <text>Password incorrect, please try again</text> 
       } 
      } 
    } 
    }//end of razor, HTML begins 
    <html> 
     <body> 
     @{ //if cookie is set 
      //if(Request.Cookies["mpUsername"] == null){ 

     } 
     <h2>ACCOUNT MANAGEMENT</h2> 
     @{ 
      } else {//user not logged in, cookie not set 
     } 
     //login form 
     </body> 
    </html> 

做我想做的事情的最佳方式是什么?在我的实际代码中,登录表单和帐户管理页面显然要大得多,所以它有点混乱,因此我从上面的代码中移除了这些。

+2

你有没有考虑过使用FormsAuthentication? http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.aspx – 2012-02-20 15:20:10

+0

是的,但我不认为这将支持我希望身份验证运行 - 我正在验证用户登录信息针对远程服务器而不是本地存储的服务器。 – 2012-02-20 15:24:44

+1

我同意Pauli - 使用内置系统。很容易错过某些东西/留下一个安全漏洞。 – Paddy 2012-02-20 15:24:54

回答

0

这将帮助您了解Cookies in ASP.NET using C#

+1

虽然所提供的链接是一个很好的资源,但即使该页面被移动,在页面上提供答案也是一个好主意,并且将该链接引用为更多信息的来源。 – mgrenier 2015-02-05 15:05:36