2011年9月22日

[WCF] Passing & Retrieving message header in basicHttpBinding Services

To send message properties to the server.


  1: var svc = new GPServiceFactory().GetInboxService();
  2: using (new OperationContextScope(((IClientChannel)svc))) {
  3:  OperationContext oc = OperationContext.Current;
  4:  HttpRequestMessageProperty httpRequestProperty = null;
  5:   if (oc.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) {
  6:   httpRequestProperty =
  7:    oc.OutgoingMessageProperties[HttpRequestMessageProperty.Name]
  8:      as HttpRequestMessageProperty;
  9:    }
 10: 
 11:    if (httpRequestProperty == null) {
 12:     httpRequestProperty = new HttpRequestMessageProperty();        
 13:    }
 14:    httpRequestProperty.Headers.Add("ClientTimeZone", param["TimeZone"]);
 15:    oc.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
 16:    return svc.GetWorkitemsInQueue(appId, UserId, queueName, 1000, 1);
 17: }

 


To retrieve properties

  1: Dictionary<String, String> param = null;
  2: try {
  3:  if (OperationContext.Current.IncomingMessageProperties.Keys != null) {
  4:   param = new Dictionary<string, string>();
  5:    foreach (var key in (OperationContext.Current.IncomingMessageProperties.Keys)) {
  6:     if (System.ServiceModel.OperationContext.Current.IncomingMessageProperties[key] is HttpRequestMessageProperty) {
  7:      var p = OperationContext.Current.IncomingMessageProperties[key] as HttpRequestMessageProperty;
  8:       foreach (string k in p.Headers.AllKeys) {
  9:        if (k.Equals("timezone", StringComparison.OrdinalIgnoreCase)) {
 10:         string v = p.Headers[k].StartsWith("+") ? p.Headers[k].Substring(1) : p.Headers[k];
 11:         param.Add("TimeZone", v);
 12:        }
 13:        else {
 14:         param.Add(k, p.Headers[k]);
 15:        }
 16:      }
 17:    }
 18:  }
 19: }

沒有留言:

Blog Archive

About Me