我有以下网络服务代码
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1, Name = "Service1")]
[ToolboxItem(false)]
public partial class Service1 : System.Web.Services.WebService
{
public SessionCredentials sessionHeader = new SessionCredentials();
public class SessionCredentials{
public Guid SessionID = Guid.Empty;
}
private bool IsLoggedIn
{
get
{
return (sessionHeader != null && sessionHeader.SessionID != Guid.Empty);
}
}
[SoapDocumentMethod(Binding = "Service1")]
[WebMethod]
[SoapHeader("sessionHeader")]
public System.Data.DataTable GetVisitList(Guid facilityID)
{
if (IsLoggedIn)
{
try
{
return test;
}
catch (Exception ex)
{
return null;
}
}
return null;
}
}
在调用此服务时,这没有问题。现在我使用以下代码将webservice迁移到WCF
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1, Name = "Service1")]
[ToolboxItem(false)]
[ServiceContract(Namespace = "http://tempuri.org")]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public partial class Service1 : System.Web.Services.WebService
{
public SessionCredentials sessionHeader = new SessionCredentials();
public class SessionCredentials{
public Guid SessionID = Guid.Empty;
}
private bool IsLoggedIn
{
get
{
return (sessionHeader != null && sessionHeader.SessionID != Guid.Empty);
}
}
[OperationContract]
public void SetCredentials(SessionCredentials session)
{
sessionHeader = session;
}
[SoapDocumentMethod(Binding = "Service1")]
[WebMethod]
[SoapHeader("sessionHeader")]
[OperationContract]
public System.Data.DataTable GetVisitList(Guid facilityID)
{
if (IsLoggedIn)
{
try
{
return test;
}
catch (Exception ex)
{
return null;
}
}
return null;
}
}
我也用这个
更新web.config文件 <system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<!--<service name="webservice" behaviorConfiguration="returnFaults">
<endpoint binding="basicHttpBinding" contract="webservice"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>-->
<service name="webservice" behaviorConfiguration="returnFaults">
<endpoint binding="basicHttpBinding"
contract="Service"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="returnFaults">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
不知何故,当我在客户端调用GetVisitList时,我总是得到IsLoggedIn返回false,即使我在调用此方法之前设置了sessionid。请在这里帮忙。
答案 0 :(得分:0)
要保留sessionHeader实例,您必须将服务实例设置为Single,否则每个调用都将获得自己的实例
在服务类中使用 InstanceContextMode = InstanceContextMode.Single :
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single]
public partial class Service1 : System.Web.Services.WebService
希望它有所帮助。
答案 1 :(得分:0)
实际上我只创建了一个静态变量并存储了sessionid,每当我调用另一个方法时,该值仍然存在于上下文中。