我在SQL Server表中有一个可以为空的GUID列,我试图使用我的Web应用程序中的log4net存储过程进行更新 .
我使用this blog article中描述的属性提供程序方法作为在 Application_BeginRequest
期间在log4net LogicalThreadContext中设置属性的最佳实践,以利用在运行时log4net将调用对象的 ToString
方法来获取值而不会被ASP破坏的事实.NET线程切换:
protected void Application_BeginRequest() {
log4net.LogicalThreadContext.Properties["userid"] = new UserIdProvider();
这是UserIdProvider:
public class UserIdProvider {
public Guid IConvertible() { //attempt at resolving error on IConvertible
if (HttpContext.Current.Request.IsAuthenticated) {
MembershipUser myObject = Membership.GetUser();
Guid currentUserID = (Guid)myObject.ProviderUserKey;
return currentUserID;
}
else {
return Guid.Empty;
}
}
public override string ToString() {
if (HttpContext.Current.Request.IsAuthenticated) {
MembershipUser myObject = Membership.GetUser();
Guid currentUserID = (Guid)myObject.ProviderUserKey;
return currentUserID.ToString();
}
else {
return null;
}
}
}
和log4net布局属性是:
<parameter>
<parameterName value="@UserID" />
<dbType value="Guid" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="userid" />
</layout>
</parameter>
使用userid提供程序log4net会抛出异常:
log4net:ERROR [AdoNetAppender] Exception while writing to database
System.InvalidCastException: Failed to convert parameter value from a
UserIdProvider to a Guid. ---> System.InvalidCastException: Object must
implement IConvertible.
在看到这个后,我将公共Guid IConvertible()位添加到提供者,但在黑暗中它有点刺 .
我也试过看看我是否可以尝试使用log4net,并告诉它dbType是字符串,看它是否会使用ToString()覆盖并将参数传递给存储过程,但它导致了这个异常:
log4net:ERROR [AdoNetAppender] Exception while writing to database
System.InvalidCastException: Failed to convert parameter value from a
UserIdProvider to a String. ---> System.InvalidCastException: Object
must implement IConvertible.
我相信我需要使用RawPropertyLayout来获取log4net来传递空值 . 我从其他属于nullable int或nullable datetime的属性中知道这一点 .
我编写IConvertible方法的方式有问题,还是我需要将UserIdProvider放在一起以返回GUID?
1 回答
你实际上并不是 implementing IConvertible
你的课需要被定义为
...
当你这样做时,你可能会发现你需要添加更多的方法 .
有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/tyz9cd4z.aspx