在ASP.NET MVC中实现自定义配置文件提供 [英] Implementing Custom Profile Provider in ASP.NET MVC
问题描述
我试过了很多实施ASP.NET MVC自定义配置文件提供者。
我读过很多很多的教程,但我找不到在哪里我的问题。它类似于Implementing配置文件提供在ASP.NET MVC 。
I tried a lot on implementing a custom profile provider in ASP.NET MVC. I've read lots and lots of tutorials, but I can't find where my problem is. It's pretty similar to Implementing Profile Provider in ASP.NET MVC.
不过,我想创建自己的个人资料提供者,所以我写了下面的类,从继承 ProfileProvider
:
But I'd like to create my own Profile Provider, so I wrote the following class that inherits from 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:
Here is my CreateProfile action in my Controller:
[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什么特别的:
My procedure usp_GetUserProcedure is nothing special:
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文件:
And my Web.Config file:
<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>
不过,我总是得到此异常:
But I always get this exception:
过程或函数'usp_GetUserProcedure'需要参数'@firstName,这是没有提供。
Procedure or function 'usp_GetUserProcedure' expects parameter '@FirstName', which was not supplied.
这是什么,我可能是做错了任何想法?
Any thoughts on what I might be doing wrong?
推荐答案
最可能的原因是,
myCommand.Parameters.AddWithValue("@FirstName", (string)context["FirstName"]);
(字符串)范围内[名字]
是一个空值。即使你一个参数传递给一个存储过程,如果该值是必需的参数为空,然后你会看到这个错误。 SQL Server的(有效)没有参数区分不过去了,一个具有空值传递的。
(string)context["FirstName"]
is a null value. Even if you pass in a parameter to a sproc, if the value is null on a required parameter, then you will see this error. SQL Server (effectively) does not differentiate between a parameter not passed, and one passed with a null value.
您所看到SQL错误。这是无关的MVC和MVC是不是真的造成您的问题。确定是否为null是一个有效的值背景[名字]
,如果是的话,改变你的函数接受空值。如果不是,找出原因背景[名字]
为null。
You're seeing a SQL error. This is unrelated to MVC and MVC isn't really causing your problem. Determine if null is a valid value context["FirstName"]
, and if so, change your function to accept null values. If not, find out why context["FirstName"]
is null.
另外,我不认为此行是要正确地添加参数名称(用@preFIX)。
Also, I don't think this line is going to add your parameter names correctly (with the "@" prefix).
myCommand.Parameters.AddWithValue(value.Name,value.PropertyValue);
myCommand.Parameters.AddWithValue(value.Name, value.PropertyValue);
此外,由于这是MVC,确保你有一个控制的的命名的名字的形式张贴到:
Also, since this is MVC, make sure you have a control named FirstName on the form posting to:
public ActionResult CreateProfile(string Username, string Password, string FirstName, string LastName)
它读取基于名称字段,不是ID
It reads fields based on the name, not the ID
这篇关于在ASP.NET MVC中实现自定义配置文件提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!