This is a mirror of official site: http://jasper-net.blogspot.com/

Send Cookies When Making WCF Service Calls

| Wednesday, May 4, 2011
Introduction

This article presents an example on how to send cookies when making WCF service calls.
Background

Once a while, you may find that you want to send some information in the form of "Cookies" to the server when making WCF calls. For example, if the WCF service is protected by a "Forms Authentication" mechanism, you will need to send the authentication cookie when making the WCF call to gain the required access to the service.

If you are calling a "REST" service using the "WebClient" class, this should not be a difficult task. You can simply work on the "CookieContainer" property of the "HttpWebRequest" class.
If you are calling a regular WCF service, and your client proxies are generated by the "Adding service reference" tool in the Visual Studio, the method to send cookies is not so obvious.
This article is to present an example on how to send cookies when making WCF calls using the Visual Studio generated client proxies.

The WCF service

The example WCF service is implemented in the "ServiceWithCookies.svc.cs" file in the "WCFHost" project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.ServiceModel.Activation;
 
namespace WCFHost
{
    [DataContract]
    public class CookieInformation
    {
        [DataMember(Order = 0)]
        public string Key { get; set; }
        [DataMember(Order = 1)]
        public string Value { get; set; }
    }
 
    [ServiceContract]
    public interface IServiceWithCookies
    {
        [OperationContract]
        CookieInformation EchoCookieInformation();
    }
 
    [AspNetCompatibilityRequirements(RequirementsMode
        = AspNetCompatibilityRequirementsMode.Required)]
    public class ServiceWithCookies : IServiceWithCookies
    {
        public CookieInformation EchoCookieInformation()
        {
            var request = HttpContext.Current.Request;
            string key = "NA";
            string value = "NA";
 
            if (request.Cookies.Count > 0)
            {
                key = request.Cookies.Keys[0];
                value = request.Cookies[key].Value;
            }

Read more: Codeproject

Posted via email from Jasper-net

0 comments: