Search code examples
wcf-data-servicesodata

wcf data services - passing extra params on save changes


I have an existing web application that I want to wrap with WCF Data Services, to give it an OData input/output formatting.

in retrieving records, I can send whatever I like (myusername = "blabala", mycurrentusersession = "23434sdfgdf" and so on...). But in "SaveChanges" I do not control what is sent - though, I realy need the ability to supply the existing application : - my current user session - the specific retrieve state key (my existing application is stateful)


Solution

  • you can add these values in header of the outgoing request.

    Suppose, you did "Add Service Reference" in your Client app, of your WCF-DataService.

    then inside Reference.cs of the service(on the client), search for OnContextCreated event:

    and then, add a handler to SendingRequest event

    partial void OnContextCreated() 
    { 
       this.SendingRequest += Entity_SendingRequest; 
    }
    

    and inside Entity_SendingRequest you can add headers.

    void Entity_SendingRequest(object sender, SendingRequestEventArgs e) 
    { 
       e.RequestHeaders.Add("myusername", "blabala");
       e.RequestHeaders.Add("mycurrentusersession", "23434sdfgdf");
    }
    

    which you can very easily process at the Server End i.e. in the DataContext of WCF-DataService.

    you can also pass a CookieContainer. That's the basis of Forms Authentication for WCF-Data Services.

    void Entity_SendingRequest(object sender, SendingRequestEventArgs e) 
    { 
       CookieContainer cookieContainer = new CookieContainer();
       foreach (var cc in _cookies)
       {
           Cookie cookie = new Cookie(cc.Key, cc.Value.Value);
           cookieContainer.Add(new Uri("http://localhost", UriKind.Absolute), cookie);
       }
       var cookieHeader = cookieContainer.GetCookieHeader(new Uri("http://localhost", 
                                                                UriKind.Absolute));
        e.RequestHeaders["Cookie"] = cookieHeader;
    }