当实例上下文模式设置为每个会话或每个调用时获取异常



我正在尝试制作一个可以登录的应用程序(出于学习目的(,并将创建一个"user"实例,然后将他们的用户ID保存在其中。然后,他们可以调用 getUserid 方法并获取他们保存的用户 ID。但是如果我使用单个实例上下文模式,旧用户的用户 ID 将被新用户替换。所以我正在尝试每个会话模式,但是当我在登录后调用getUserid方法时,我收到以下异常。

Server stack trace: 
At System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]: 
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IService.getUserid()
at ServiceClient.getUserid()

这是我的服务类代码。

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService
{
SqlConnection con;
SqlCommand command;
SqlDataReader sdr;
user loginUser;
public Service()
{
dataBase();
}
public bool Login(string username, string password)
{
command.CommandText = "select userid, password from chatuser where username = '" + username + "'";
sdr = command.ExecuteReader();
while (sdr.Read())
{
if (password.Equals(sdr.GetString(1)))
{
loginUser = new user(sdr.GetString(0));
return true;
}
}
return false;
}
public string getUserid()
{
return loginUser.Userid;
}
}

这是我的用户类。

[DataContract]
public class user
{
string userid;
public user()
{
}
public user(string userid)
{
this.userid = userid;
}
[DataMember]
public string Userid
{
get { return userid; }
set { userid = value; }
}
}

这是我的接口类。

[ServiceContract]
public interface IService
{
[OperationContract]
bool Login(string username, string password);
[OperationContract]
string getUserid();
}

将 InstanceContextMode 更改为按会话后发生错误,应用在单个时运行良好,但新应用将替换旧应用。那么它是否仍应设置为每个会话?还是我做错了什么?

我是自学 C# 并且是新手,所以如果我问愚蠢的问题,我很抱歉。

我正在使用basicHttpsBinding

好吧,这就是问题所在,因为basicHttpsBinding不支持Session(默认情况下(,因此如果您使用PerSessionInstanceContextMode它必然会抛出异常,因为没有会话。

在这种情况下,您应该使用netTcpBindingwsHttpBinding,它具有Session设施

最新更新