I have a WCF data service on my asp.net website that looks like:
public class WcfDataService : DataService<MyEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
protected override Data.Sub.TcSubEntities CreateDataSource()
{
// if user is logged in enable him to query database otherwise do not
if (HttpContext.Current.Session["user"] != null)
{
return base.CreateDataSource();
}
else
{
return null;
}
}
}
My client first calls the page myDomain.com/Authenticate.aspx then I set HttpContext.Current.Session["user"]
equal to the id of the user.
Anyways the client is a console application and I have set a reference to that data service. The way I want to query the database is like:
var db = new ServiceReference.MyEntities(new Uri("MyDomain/WcfDataService.svc"));
var customers = db.Customers.ToList();
I use How do I log into a site with WebClient? In order to be able to access pages on my website. how could I use that webclient to connect to my wcf data service so that I could use the same session?
PS
If I have the session id could I pass that through the url as a parameter?
Finally found the solution. I manage how to add cookies to the request. On the client I did:
Note I am using a cookie aware webclient from: Using CookieContainer with WebClient class
var cookieAwareWebClient= //.... authenticate
var db = new ServiceReference.MyEntities(new Uri("MyDomain/WcfDataService.svc"));
db.SendingRequest += ( s, arg) =>
{
HttpWebRequest httpRequest = arg.Request as HttpWebRequest;
httpRequest.CookieContainer = cookieAwareWebClient.CookieContainer; // I made that property public
};
var myUsers = db.Users.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.