如何在 wcf 服务中拥有会话 ID
我正在编写一个具有多种方法的身份验证服务。其中一个方法是 ChangePassword。我希望当任何人想要更改密码时,先登录到系统。为此,我想要一个会话 ID,并在更改密码之前检查它。
我该如何做到这一点并且该会话超时?
编辑1)
我编写了这段代码,但每次我想获取它的值时,我的会话都是空的:
Class:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service2 : IService2
{
string result
{ // Store result in AspNet session.
get
{
if (HttpContext.Current.Session["Result"] != null)
return HttpContext.Current.Session["Result"].ToString();
return "Session Is Null";
}
set
{
HttpContext.Current.Session["Result"] = value;
}
}
public void SetSession(string Val)
{
result = Val;
}
public string GetSession()
{
return result;
}
interface:
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IService2
{
[OperationContract]
void SetSession(string Val);
[OperationContract]
string GetSession();
}
web.config
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
编辑2) 我写了这段代码,但它不起作用:
private void button1_Click(object sender, EventArgs e)
{
MyService2.Service2Client srv = new MyService2.Service2Client();
textBox1.Text = srv.GetSession();
}
private void button2_Click(object sender, EventArgs e)
{
MyService2.Service2Client srv = new MyService2.Service2Client();
srv.SetSession(textBox1.Text);
textBox1.Clear();
}
每次我想获取会话值时,我都会得到“会话为空”。为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在WCF中使用wsHttpBinding时,您会发现OperationContext.Current.SessionId的值为null。
解决方案如下(需要两步):
在配置文件中将reliableSession启用为true
<前><代码><绑定>;
;
<绑定名称=“WSHttpBinding_MyService”sendTimeout=“00:05:00”>
<安全模式=“无”>
在合约界面中,将SessionMode属性设置为Required
按照上面的步骤,问题就解决了
When use wsHttpBinding in WCF you will find the value of OperationContext.Current.SessionId is null.
The Solution is as follows(need two steps):
Enable reliableSession to true in the configuration file
In the contract interface, have SessionMode attribute set to Required
Follow the steps above, the problem will be solved
您可以在 WCF 服务中激活 ASP.NET 兼容模式,并享受 ASP.NET 会话和上下文的所有优势。
将此属性添加到您的 WCF 类定义中:
以及您的 web.config 中:
You can activate the ASP.NET compatibility mode in your WCF service, and have all the benefits of ASP.NET sessions and context.
Add this attribute to your WCF class definition:
and in your web.config:
为了拥有 SessionId,您必须具有启用会话的绑定。例如,
wsHttpBinding
。在您的配置文件中,您应该具有类似以下内容:在
IMyService
接口中,您必须将SessionMode
属性设置为Required
,如下所示:当所有这些都设置完毕后,您可以像这样获取
SessionId
:另一种方法是启用 AspNetCompatibilityRequirements,但仅仅获取 SessionId 有点过分了。
In order to have SessionId, you have to have Session-enabled binding. For example,
wsHttpBinding
. In your config file, you should have something like:In the
IMyService
interface, you have to haveSessionMode
attribute set toRequired
, like so:When all of this is setup, you can get to the
SessionId
like this:Another way would be to enable AspNetCompatibilityRequirements but it's a bit of an overkill just to get the SessionId.