来自web.config文件的SQL连接

时间:2016-01-08 10:22:30

标签: c# asp.net sql-server

我的web.config代码:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
  </appSettings>
  <system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
          assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
    </authentication>
    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
      </providers>
    </membership>
    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
      </providers>
    </roleManager>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
        path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
 <connectionStrings>
   <add name="SQLDbConnection"
        connectionString="Server=DESKTOP-LRT15J5; Database=FYP_1;"
        providerName="System.Data.SqlClient" />
 </connectionStrings>
</configuration>

这是我的后端代码

我的后端代码:

protected void btnLogin_Click(object sender, EventArgs e)
{
    string username = txt_username.Text;
    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString))
    {
        conn.Open();

        string sqlUserName;
        sqlUserName = " select user_name, password from Login_Table where user_name='" + txt_username.Text + "' AND password='" + txt_Pwd.Text + "'  ";
        using (SqlCommand cmd = new SqlCommand(sqlUserName, conn))
        {
            string currentname;
            currentname = (string)cmd.ExecuteScalar();
            if (currentname != null)
            {
                Session["myusername"] = username;

                Response.Redirect("~/Admin/Adminpannel.aspx");

            }
            else
            {
                lblMsg.Text = "Your Name OR Password is Not Correct OR You are Not Register";

            }
        }
    }
}

这是我的错误

  

错误:

     

类型&#39; System.Data.SqlClient.SqlException&#39;的异常发生在   System.Data.dll但未在用户代码中处理

     

其他信息:用户登录失败&#39; <#39;。

3 个答案:

答案 0 :(得分:2)

您错过了连接字符串中的User IDPassword

 <add name="SQLDbConnection"
    connectionString="Server=DESKTOP-LRT15J5; Database=FYP_1;User Id=myUsername;Password=myPassword;"
    providerName="System.Data.SqlClient" />

请查看:SQL Server connection strings

另外,我强烈建议您始终使用parameterized queries来避免SQL Injection。像这样:

sqlUserName = "select user_name, password from Login_Table where user_name= @username AND password= @password";
cmd.Parameters.AddWithValue("@username", txt_username.Text);
cmd.Parameters.AddWithValue("@password",  txt_Pwd.Text);

答案 1 :(得分:0)

所以问题是你没有在配置中提供登录凭据,这是获得数据库认证的必要条件。所以包括

uid=myUser;password=myPass;

以下是您的一个示例:

<appSettings>
<add name="SQLDbConnection" connectionString="Data Source=DESKTOP-LRT15J5;database=myDb;uid=myUser;password=myPass;" />
</appSettings>

refer for more

答案 2 :(得分:0)

问题发生在conn.Open。您需要提供应用程序如何连接数据服务器。

这是用于Windows身份验证的;

<connectionStrings>        
    <add name="SQLDbConnection" connectionString="Data Source=DESKTOP-LRT15J5;Initial Catalog=FYP_1;Integrated Security=True"/>
  </connectionStrings>

或Sql server身份验证

<connectionStrings>        
        <add name="SQLDbConnection" connectionString="Data Source=DESKTOP-LRT15J5;Initial Catalog=FYP_1;Integrated Security=False;User Id=Username;Password=Password"/>
</connectionStrings>