位置:海鸟网 > IT > ASP.NET >

利用WCF共享ASP.NET session实现WCF服务端验证

WCF能够共享ASP.NET的session,不同的WCF客户端代理类在采用Per Call模式下访问WCF能够访问同一个ASP.NET Session.但是WCF的Session和ASP.NET的Session是不同的。

  • WCF的Session代表着服务实例,它是被客户端代理类访问时初始化的。WCF依靠消息通道,安全回话和消息模式等来联系session的。
  • 而ASP.NET的session是类似服务端的一种存储数据的模式。它是通过客户端cookie和uri来维护session的
  • 利用ASP.NET的session实现认证,在aspx里记录用户认证信息:  
  • Timeout = HttpContext.Current.Session.Timeout;

      2.  如果WCF服务端能够共享Asp.NET的session,必须在WCF配置文件中进行如下设置:

    />

      3. 在服务端新建一个用户类:

    UserHelper
    SessionUserKey = ;
    4
    UserInfo CurrentUser
    (!HttpContext.Current.User.Identity.IsAuthenticated)
    ]);
    ;
    16 }
    17
    user = null;
    20
    21 if(HttpContext.Current.Session != null)
    22 user = HttpContext.Current.Session[key];
    23
    info = HttpContext.Current.Session[key] = info;
    (UserInfo)user;
    AdminService : IAdminService
    InsertAdmin(Admin admin)
    (!UserHelper.CurrentUser == ,

    FaultException<CustomerFaultException>(exception);
    adminDal.InsertAdmin(admin);
    ;
    (new OperationContextScope((IContextChannel)proxy))
    ));
    7 HttpResponseMessageProperty responseProperty = OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name]
    8 as HttpResponseMessageProperty;
    9 helper = HttpSessionCookieHelper.Create((string)responseProperty.Headers[HttpResponseHeader.SetCookie]);
    10 }
    11
    AspNetSessionIdCookieName = ;
    4 string aspNetSessionId = string.Empty;
    5 HttpSessionCookieHelper()
    6 { }
    7
    HttpSessionCookieHelper Create(string cookieString)
    9 {
    10 HttpSessionCookieHelper helper = new HttpSessionCookieHelper();
    11 helper.ParseCookieString(cookieString);
    12 return helper;
    13 }
    14
    HttpSessionCookieHelper CreateFromSessionId(string sessionId)
    16 {
    17 HttpSessionCookieHelper helper = new HttpSessionCookieHelper();
    18 helper.aspNetSessionId = sessionId;
    19 return helper;
    20 }
    21
    AddSessionIdToRequest(HttpRequestMessageProperty requestProperty)
    ;
    26
    , AspNetSessionIdCookieName, (, cookieString, sessionCookieString);
    36 }
    37
    38 requestProperty.Headers[HttpRequestHeader.Cookie] = cookieString;
    39 }
    40
    (string.IsNullOrEmpty(cookieString))
    44 return;
    45
    );
    [] cookieNameValues = cookies[i].Split();
    .aspNetSessionId = cookieNameValues[1];
    53 return;
    54 }
    55 }
    56 }
    57
    AspNetSessionId
    .aspNetSessionId;
    ());
    10 }
    11
    12 ((IClientChannel)proxy).Close();
    13
    14 if (Interlocked.Increment(ref completedCount) == 2)
    15 {
    16 waitHandle.Set();
    17 }
    18 }