对象引用未设置为对象数据库用户名验证的实例

时间:2014-03-06 22:52:49

标签: c# asp.net nullreferenceexception

我无法理解connectionString命令背后的逻辑。我正在尝试创建用户名注册页面,在提交之前检查用户名的可用性。我已经按照我的ASP.NET释放的教科书来发球,但我仍然得到“对象参考未设置”错误。我必须在此处相应地命名我的数据库和表格,还是我错过了其他的东西?我一直在疯狂地搜索互联网,试图理解这一点,但我只是在困惑自己。任何建议将不胜感激。

以下是我的ShowAjaxValidator.aspx和AjaxValidator.cs页面:

<%@ Page Language="C#" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    /// <summary>
    /// Validation function that is called on both the client and server
    /// </summary>
    protected void AjaxValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (UserNameExists(args.Value))
            args.IsValid = false;
        else
            args.IsValid = true;
    }

    /// <summary>
    /// Returns true when user name already exists
    /// in Users database table
    /// </summary>
    private bool UserNameExists(string userName)
    {
        string conString =
WebConfigurationManager.ConnectionStrings["UsersDB"].ConnectionString;
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName=@UserName", con);
        cmd.Parameters.AddWithValue("@UserName", userName);
        bool result = false;
        using (con)
        {
            con.Open();
            int count = (int)cmd.ExecuteScalar();
            if (count > 0)
                result = true;
        }
        return result;
    }

    /// <summary>
    /// Insert new user name to Users database table
    /// </summary>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string conString =
WebConfigurationManager.ConnectionStrings["UsersDB"].ConnectionString;
        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand("INSERT Users (UserName,FavoriteColor) VALUES (@UserName,@FavoriteColor)", con);
        cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
        cmd.Parameters.AddWithValue("@FavoriteColor", txtFavoriteColor.Text);
        using (con)
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        txtUserName.Text = String.Empty;
        txtFavoriteColor.Text = String.Empty;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show AjaxValidator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:Label
        id="lblUserName"
        Text="User Name:"
        AssociatedControlID="txtUserName"
        Runat="server" />
    <asp:TextBox
        id="txtUserName"
        Runat="server" />
    <custom:AjaxValidator
        id="AjaxValidator1"
        ControlToValidate="txtUserName"
        Text="User name already taken!"
        OnServerValidate="AjaxValidator1_ServerValidate"
        Runat="server" />

    <br /><br />
    <asp:Label
        id="lblFavoriteColor"
        Text="Favorite Color:"
        AssociatedControlID="txtFavoriteColor"
        Runat="server" />
    <asp:TextBox
        id="txtFavoriteColor"
        Runat="server" />

    <br /><br />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" OnClick="btnSubmit_Click" />

    </div>
    </form>
</body>
</html>

AjaxValidator.cs

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace myControls
{
    /// <summary>
    /// Enables you to perform custom validation on both the client and server
    /// </summary>
    public class AjaxValidator : BaseValidator, ICallbackEventHandler
    {
        public event ServerValidateEventHandler ServerValidate;

        string _controlToValidateValue;

        protected override void OnPreRender(EventArgs e)
        {
            String eventRef = Page.ClientScript.GetCallbackEventReference
              (
                this,
                "",
                "",
                ""
              );

            // Register include file
            String includeScript =
                  Page.ResolveClientUrl("~/ClientScripts/AjaxValidator.js");
            Page.ClientScript.RegisterClientScriptInclude("AjaxValidator",
                  includeScript);

            // Register startup script
            String startupScript =
String.Format("document.getElementById('{0}').evaluationfunction = 'AjaxValidatorEvaluateIsValid';", this.ClientID);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "AjaxValidator", startupScript, true);

            base.OnPreRender(e);
        }

        /// <summary>
        /// Only do the AJAX on browsers that support it
        /// </summary>
        protected override bool DetermineRenderUplevel()
        {
            return Context.Request.Browser.SupportsCallback;
        }

        /// <summary>
        /// Server method called by client AJAX call
        /// </summary>
        public string GetCallbackResult()
        {
            return ExecuteValidationFunction(_controlToValidateValue).ToString();
        }

        /// <summary>
        /// Return callback result to client
        /// </summary>
        public void RaiseCallbackEvent(string eventArgument)
        {
            _controlToValidateValue = eventArgument;
        }

        /// <summary>
        /// Server-side method for validation
        /// </summary>
        protected override bool EvaluateIsValid()
        {
            string controlToValidateValue =
this.GetControlValidationValue(this.ControlToValidate);
            return ExecuteValidationFunction(controlToValidateValue);
        }

        /// <summary>
        /// Performs the validation for both server and client
        /// </summary>
        private bool ExecuteValidationFunction(String controlToValidateValue)
        {
            ServerValidateEventArgs args = new ServerValidateEventArgs (controlToValidateValue, this.IsValid);
            if (ServerValidate != null)
                ServerValidate(this, args);
            return args.IsValid;
        }

    }

}

我遇到的错误指向.aspx文件的一部分:

string conString =
WebConfigurationManager.ConnectionStrings["UsersDB"].ConnectionString;

错误表示用户无法处理空异常,并且“对象引用未设置为对象的实例”。

我尝试将connectionStrings添加到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>
  <connectionStrings>
    <add name="UsersDB"
         providerName="System.Data.SqlClient"
         connectionString="Data Source=.\SQLExpress;
                    AttachDbFilename=|DataDirectory|UsersDB.mdf;
                    Integrated Security=True;User Instance=True" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

我现在收到一个SqlException,说: 尝试为文件C:\ Users \ Mike \ Documents \ Visual Studio 2010 \ WebSites \ Validation_Attempt \ App_Data \ UsersDB.mdf附加自动命名的数据库失败。存在具有相同名称的数据库,或者无法打开指定的文件,或者它位于UNC共享上。

我是ASP和C#的新手。编辑青铜。

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试读取不存在的配置值,然后访问该空对象上的属性。

您的web.config文件中需要一个connectionStrings节点,该节点的密钥为UsersDB,其中包含数据库的连接字符串。没有它,该对象为null并且调用ConnectionString属性会抛出空引用异常。解决该设置后,此属性将正常运行。