【问题标题】:Implementing Custom Profile Provider in ASP.NET MVC在 ASP.NET MVC 中实现自定义配置文件提供程序
【发布时间】:2010-10-24 11:10:54
【问题描述】:

我尝试了很多在 ASP.NET MVC 中实现自定义配置文件提供程序。 我已经阅读了很多很多教程,但我找不到我的问题所在。它与Implementing Profile Provider in ASP.NET MVC 非常相似。

但我想创建自己的 Profile Provider,所以我编写了以下继承自 ProfileProvider 的类:

public class UserProfileProvider : ProfileProvider
{
    #region Variables
    public override string ApplicationName { get; set; }
    public string ConnectionString { get; set; }
    public string UpdateProcedure { get; set; }
    public string GetProcedure { get; set; }
    #endregion

    #region Methods
    public UserProfileProvider()
    {  }

    internal static string GetConnectionString(string specifiedConnectionString)
    {
        if (String.IsNullOrEmpty(specifiedConnectionString))
            return null;

        // Check <connectionStrings> config section for this connection string
        ConnectionStringSettings connObj = ConfigurationManager.ConnectionStrings[specifiedConnectionString];
        if (connObj != null)
            return connObj.ConnectionString;

        return null;
    }
    #endregion

    #region ProfileProvider Methods Implementation
    public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
    {
        if (config == null)
            throw new ArgumentNullException("config");

        if (String.IsNullOrEmpty(name))
            name = "UserProfileProvider";

        if (String.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "My user custom profile provider");
        }

        base.Initialize(name, config);

        if (String.IsNullOrEmpty(config["connectionStringName"]))
            throw new ProviderException("connectionStringName not specified");

        ConnectionString = GetConnectionString(config["connectionStringName"]);

        if (String.IsNullOrEmpty(ConnectionString))
            throw new ProviderException("connectionStringName not specified");


        if ((config["applicationName"] == null) || String.IsNullOrEmpty(config["applicationName"]))
            ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
        else
            ApplicationName = config["applicationName"];

        if (ApplicationName.Length > 256)
            throw new ProviderException("Application name too long");

        UpdateProcedure = config["updateUserProcedure"];
        if (String.IsNullOrEmpty(UpdateProcedure))
            throw new ProviderException("updateUserProcedure not specified");

        GetProcedure = config["getUserProcedure"];
        if (String.IsNullOrEmpty(GetProcedure))
            throw new ProviderException("getUserProcedure not specified");
    }

    public override System.Configuration.SettingsPropertyValueCollection GetPropertyValues(System.Configuration.SettingsContext context, System.Configuration.SettingsPropertyCollection collection)
    {
        SettingsPropertyValueCollection values = new SettingsPropertyValueCollection();

        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlCommand myCommand = new SqlCommand(GetProcedure, myConnection);
        myCommand.CommandType = CommandType.StoredProcedure;

        myCommand.Parameters.AddWithValue("@FirstName", (string)context["FirstName"]);

        try
        {
            myConnection.Open();
            SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.SingleRow);

            reader.Read();

            foreach (SettingsProperty property in collection)
            {
                SettingsPropertyValue value = new SettingsPropertyValue(property);

                if (reader.HasRows)
                {
                    value.PropertyValue = reader[property.Name];
                    values.Add(value);
                }
            }

        }
        finally
        {
            myConnection.Close();
            myCommand.Dispose();
        }

        return values;
    }

    public override void SetPropertyValues(System.Configuration.SettingsContext context, System.Configuration.SettingsPropertyValueCollection collection)
    {
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlCommand myCommand = new SqlCommand(UpdateProcedure, myConnection);
        myCommand.CommandType = CommandType.StoredProcedure;

        foreach (SettingsPropertyValue value in collection)
        {
            myCommand.Parameters.AddWithValue(value.Name, value.PropertyValue);
        }

        myCommand.Parameters.AddWithValue("@FirstName", (string)context["FirstName"]);

        try
        {
            myConnection.Open();
            myCommand.ExecuteNonQuery();
        }

        finally
        {
            myConnection.Close();
            myCommand.Dispose();
        }
    }

这是我在控制器中的 CreateProfile 操作:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateProfile(string Username, string Password, string FirstName, string LastName)
{
    MembershipCreateStatus IsCreated = MembershipCreateStatus.ProviderError;
    MembershipUser user = null;

    user = Membership.CreateUser(Username, Password, "test@test.com", "Q", "A", true, out IsCreated);

    if (IsCreated == MembershipCreateStatus.Success && user != null)
    {
        ProfileCommon profile = (ProfileCommon)ProfileBase.Create(user.UserName);

        profile.FirstName = FirstName;
        profile.LastName = LastName;
        profile.Save();
    }

    return RedirectToAction("Index", "Home");
}

我的过程 usp_GetUserProcedure 没什么特别的:

ALTER PROCEDURE [dbo].[usp_GetUserProcedure] 
-- Add the parameters for the stored procedure here
@FirstName varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
SELECT * FROM dbo.Users WHERE FirstName = @FirstName
END

还有我的 Web.Config 文件:

<profile enabled="true"
         automaticSaveEnabled="false"
         defaultProvider="UserProfileProvider"
         inherits="Test.Models.ProfileCommon">
<providers>
<clear/>
<add name="UserProfileProvider"
         type="Test.Controllers.UserProfileProvider"
         connectionStringName="ApplicationServices"
         applicationName="UserProfileProvider"
         getUserProcedure="usp_GetUserProcedure"
         updateUserProcedure="usp_UpdateUserProcedure"/>
</providers>
</profile>

但我总是遇到这个异常:

过程或函数“usp_GetUserProcedure”需要参数“@FirstName”,但未提供该参数。

有什么想法我可能做错了吗?

【问题讨论】:

    标签: asp.net-mvc profile-provider


    【解决方案1】:

    最可能的原因是

    myCommand.Parameters.AddWithValue("@FirstName", (string)context["FirstName"]);
    

    (string)context["FirstName"] 是一个空值。即使您将参数传递给存储过程,如果所需参数的值为 null,您也会看到此错误。 SQL Server(实际上)不区分未传递的参数和传递空值的参数。

    您看到一个 SQL 错误。这与 MVC 无关,并且 MVC 并没有真正导致您的问题。确定 null 是否为有效值 context["FirstName"],如果是,请将您的函数更改为接受 null 值。如果不是,请找出context["FirstName"] 为空的原因。

    另外,我认为这一行不会正确添加您的参数名称(带有“@”前缀)。

    myCommand.Parameters.AddWithValue(value.Name, value.PropertyValue);

    另外,由于这是 MVC,请确保您在发布到的表单上有一个 named FirstName:

    public ActionResult CreateProfile(string Username, string Password, string FirstName, string LastName)
    

    它根据名称而不是 ID 读取字段

    【讨论】:

      【解决方案2】:

      是的,这是因为我为我的属性使用了一个类,即继承自 ProfileBase 的 ProfileCommon。

      public class ProfileCommon : ProfileBase
      {
      public virtual string Label
      {
          get
          {
              return ((string)(this.GetPropertyValue("Label")));
          }
          set
          {
              this.SetPropertyValue("Label", value);
          }
      }
      
      public virtual string FirstName
      {
          get
          {
              return ((string)(this.GetPropertyValue("FirstName")));
          }
          set
          {
              this.SetPropertyValue("FirstName", value);
          }
      }
      
      public virtual string LastName
      {
          get
          {
              return ((string)(this.GetPropertyValue("LastName")));
          }
          set
          {
              this.SetPropertyValue("LastName", value);
          }
      }
      
      public virtual ProfileCommon GetProfile(string username)
      {
          return Create(username) as ProfileCommon;
      }
      }
      

      你可以看到我在 Web.Config 文件中使用了这个类:

      <profile enabled="true"
           automaticSaveEnabled="false"
           defaultProvider="UserProfileProvider"
           inherits="Test.Models.ProfileCommon">
      [...]
      

      对于 ASP.Net MVC,如果我在 Web.Config 中编写属性,我将无法再使用 Profile.PropertyName 访问它们。也许有办法,但我没有找到任何例子。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 2019-06-01
        • 2011-03-06
        • 1970-01-01
        相关资源
        最近更新 更多