How I can have a session id in wcf Service

后端 未结 3 1348
一整个雨季
一整个雨季 2020-12-14 13:21

I\'m coding an authentication service that have multiple methods.one of this method is ChangePassword. I want when any body wants to change the password, logon to system bef

相关标签:
3条回答
  • 2020-12-14 14:02

    In order to have SessionId, you have to have Session-enabled binding. For example, wsHttpBinding. In your config file, you should have something like:

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

    In the IMyService interface, you have to have SessionMode attribute set to Required, like so:

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

    When all of this is setup, you can get to the SessionId like this:

    var sessionId = OperationContext.Current.SessionId;
    

    Another way would be to enable AspNetCompatibilityRequirements but it's a bit of an overkill just to get the SessionId.

    0 讨论(0)
  • 2020-12-14 14:17

    When use wsHttpBinding in WCF you will find the value of OperationContext.Current.SessionId is null. The Solution is as follows(need two steps):

    1. Enable reliableSession to true in the configuration file

      <bindings>
        <wsHttpBinding>
          <binding name ="WSHttpBinding_MyService" sendTimeout="00:05:00" >
            <security mode="None"></security>
            <reliableSession enabled="true"/>
          </binding>
        </wsHttpBinding>
      </bindings>
      
    2. In the contract interface, have SessionMode attribute set to Required

      [ServiceContract(SessionMode = SessionMode.Required)]
      public interface IMyService{...}
      

    Follow the steps above, the problem will be solved

    0 讨论(0)
  • 2020-12-14 14:26

    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:

    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Required)]
    

    and in your web.config:

    <configuration>
      <system.serviceModel>
          <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
      </system.serviceModel>
    </configuration>
    
    0 讨论(0)
提交回复
热议问题