加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在wcf服务中获得会话ID

发布时间:2020-12-16 01:44:11 所属栏目:百科 来源:网络整理
导读:我正在编写一个具有多种方法的身份验证服务.此方法的一部分是ChangePassword.我想当任何机构想要更改密码,之前登录系统.为此我想要一个会话ID并在更改传递之前检查它. 我怎么能这样做,并且会议时间过去了吗? 编辑1) 我写这段代码,但每次我想要得到它的值时,
我正在编写一个具有多种方法的身份验证服务.此方法的一部分是ChangePassword.我想当任何机构想要更改密码,之前登录系统.为此我想要一个会话ID并在更改传递之前检查它.

我怎么能这样做,并且会议时间过去了吗?

编辑1)

我写这段代码,但每次我想要得到它的值时,我的会话都是null:

类:

[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;
    }

接口:

[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();
    }

每次我想获得Session值时,我都会得到“Session is Null”.为什么?

解决方法

为了拥有SessionId,您必须具有启用会话的绑定.例如,wsHttpBinding.在配置文件中,您应该具有以下内容:

<services>
  <service name="MyService">
    <endpoint address="" binding="wsHttpBinding"
    bindingConfiguration="WSHttpBinding_MyServiceConfig"
    contract="IMyService">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
  </service>
  </services>

在IMyService接口中,您必须将SessionMode属性设置为Required,如下所示:

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyService
{
    [OperationContract]
    AuthenticationData Authenticate(string username,string password);
}

完成所有这些后,您可以像这样访问SessionId:

var sessionId = OperationContext.Current.SessionId;

另一种方法是启用AspNetCompatibilityRequirements但是获得SessionId只是有点过分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读