Tuesday, December 14, 2010

Pass Token with WCF payload

I think in the case of WCF , it is always better to have the business attributes as contract parameters. But we have to have some way authentication to restrict the access of the contracts too. How will we do that, I think the better option could be to pass the username/password / token along with the payload with out being part of a contract parameter.

I googled for such a simple and focused code, but could not find any finally we have to come up with out own code.

Following is the code that we can put at the client side (at Consumer Side)




   1:  using System.ServiceModel;
   2:  using System.ServiceModel.Channels;
   3:   
   4:   
   5:  protected void Button8_Click(object sender, EventArgs e)
   6:      {
   7:          FileServiceClient s = new FileServiceClient();
   8:          if (FileUpload2.HasFile)
   9:          {
  10:              try
  11:              {                
  12:                  /* Code for adding TOKEN in MessageHeader */
  13:                  //ChannelFactory<IFileService> factory = s.ChannelFactory;
  14:                  //IFileService proxy = factory.CreateChannel();
  15:                  OperationContextScope scope = new OperationContextScope(s.InnerChannel);
  16:                  Guid myToken = Guid.NewGuid();
  17:                  MessageHeader<Guid> mhg = new MessageHeader<Guid>(myToken);
  18:                  MessageHeader untyped = mhg.GetUntypedHeader("token", "ns");
  19:                  OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
  20:                  /* Code for adding TOKEN in MessageHeader */
  21:   
  22:                  s.UploadFile1("Upload\\" + Path.GetFileName(FileUpload2.PostedFile.FileName), false, FileUpload2.PostedFile.InputStream);
  23:   
  24:              }
  25:              catch (Exception ex)
  26:              {
  27:                  Label1.Text = ex.Message;
  28:                  Debug.WriteLine(ex.Message);
  29:              }
  30:          }
  31:      }
Finally at WCF Side we have to make use of the token passed using following code






   1:  public void UploadFile1(FileDataInfo file)
   2:          {
   3:              /* Code for retrieving TOKEN from MessageHeader */
   4:              Guid mytoken = OperationContext.Current.IncomingMessageHeaders.GetHeader<Guid>("token", "ns");
   5:   
   6:              
   7:          }

No comments:

Post a Comment