在wcf中启用与wsHttpBinding的会话

时间:2011-05-27 17:00:19

标签: c# wcf wshttpbinding

我写了这段代码:

接口:

public interface IService1
{
    [OperationContract]
    string Welcome(string fullName);

    [OperationContract]
    string Goodbye();

    [OperationContract]
    string GetSessionID();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}

服务:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class Service1 : IService1
{
    private string UserFullName { get; set; }

    public string GetSessionID()
    {
        var sessionId = OperationContext.Current.SessionId;
        return sessionId.ToString();
    }

    public string Welcome(string fullName) 
    { 
        UserFullName = fullName ?? "Guest"; return string.Format("Welcome back, {0}!", UserFullName); 
    }    

    public string Goodbye() 
    {
        return string.Format("Come back soon, {0}!", UserFullName ?? "Guest"); 
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

webconfig: enter image description here

为什么UserFullName总是为空?

1 个答案:

答案 0 :(得分:1)

InstanceContextMode。 PerCall 更改为 PerSession

在您的示例中,每次调用都会创建一个服务实例。