2012-09-20 31 views
0

我已經使用了一個sql語句,我要顯示當前登錄的用戶的詳細信息。但是當我運行此命令時,它無法在vb.net中使用sql顯示當前用戶詳細信息

ConnectionString = "<%$ ConnectionStrings:Details %>" 

SelectCommand = "SELECT * FROM member WHERE username = 'User.Identity.Name'" 

它不顯示任何細節,但是當我運行

SelectCommand = "SELECT * FROM member WHERE username = 'david'" 

的用戶名大衛存在於數據庫中,並顯示在Web表單只是大衛的細節。我甚至在User.Identity.Name上做了Response.Write,該語句顯示當前登錄頁面的用戶。

+0

它說的名字 「大衛」 當我跑在Visual Studio System.Web.Security.FormsIdentity調試器| {} System.Web.Security.FormsIdentity名 = 「大衛」 – user1625271

+0

authenticationtype = 「形式」 isAuthenticated =「 true「 – user1625271

回答

2

問題是您將實際的User.Identity.Name作爲字符串而不是其值。

SelectCommand = String.Format("SELECT * FROM member WHERE username = '{0}'", User.Identity.Name) 

但更好(更安全)的做法是像

SelectCommand = "SELECT * FROM member WHERE username = @UserName" 
SelectCommand.Parameters.AddWithValue("@UserName", User.Identity.Name) 

這將防止SQL注入。

編輯: 既然你在你的頁面定義這一點,你可以用下面的模板:

<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:Details %>" SelectCommand="SELECT * FROM members WHERE ([username] = @UserName)"> 
    <SelectParameters> 
     <asp:Parameter Name="UserName" Type="String" DefaultValue="" /> 
    </SelectParameters> 
</asp:SqlDataSource> 

,則默認值設置爲User.Identity.Name在服務器端:

SqlDataSource1.SelectParameters.Item(0).DefaultValue = User.Identity.Name 

更簡單的方法是使用Configure Data Source嚮導,該向導通過在設計視圖中單擊SqlDataSource對象旁邊的右箭頭可用。

+0

帶有SelectCommand.Parameters.AddWithValue的語句給我提供了錯誤,並說此屬性必須後跟一個等號和一個值。如果值在引號內,引號必須匹配 第一條語句不顯示任何錯誤我也有」 – user1625271

+0

錯誤不允許使用文字表達式,例如'<%$ ConnectionStrings:Details%>'。改爲使用」/>。 \t \t 191那是錯誤以上是不是錯誤 – user1625271

+0

」 SelectCommand =「SELECT * FROM member」它與此語句我的程序 – user1625271

相關問題