通过.NET中的Web服务调用发送cookie

时间:2012-01-03 22:16:50

标签: .net web-services soap cookiecontainer

我遇到了在.NET中为web服务调用设置cookie的问题。在使用所提供的wsdl的任何调用之前,我必须提供登录到客户端网站时获得的cookie。我有一个登录和检索cookie的方法,然后我将其传递给我的makeSearch方法(如下所示)。如您所见,我在cookieContainer中为wsdl对象设置cookie;但是,当我检查我的AdvancedSearch方法发出的请求时,我注意到提琴手没有发送cookie。客户端使用Java提供了解决方案,但是问题是将其转移到.NET。

以下是Java代码中的解决方案:( port是传入的wsdl对象)

private static void setupClient(Object port, final String cookie) throws Exception {
    Client client = ClientProxy.getClient(port); 
    HTTPConduit http = (HTTPConduit) client.getConduit();
    HTTPClientPolicy policy = http.getClient();
    if (policy == null) {
        policy = new HTTPClientPolicy();
        http.setClient(policy);
    }
    policy.setCookie(cookie);
    policy.setAutoRedirect(true);
}

我的代码如下:

public AdvancedSearchResult makeSearch(String cookie){
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
AdvancedSearchResult searchResults = new AdvancedSearchResult();
Cookie cook= new Cookie("NAME", HttpUtility.UrlEncode(cookie));
searches.CookieContainer = new CookieContainer();
searches.CookieContainer.Add(newUri(www.test.com),cook);
searchResults = searches.AdvancedSearch("search params");
return searchResults;

}

任何人都可以列出任何想法或解决方案吗?

1 个答案:

答案 0 :(得分:4)

我刚遇到同样的问题,这就是我解决的问题

var tmWebServices             = new TM_WebServices();
tmWebServices.CookieContainer = new System.Net.CookieContainer();
tmWebServices.Url             = Test_TM.tmWebServices;

var username     = "reader";  
var passwordHash = Test_TM.passwordHash_Reader;
var sessionID    =  tmWebServices.Login(username, passwordHash);

//Note that this is optional if you set these cookies from the server side
var cookie       =  new System.Net.Cookie("Session",sessionID.str());
tmWebServices.CookieContainer.Add(tmWebServices.Url.uri() , cookie); 

var guidanceItemID = "0c85a318-0c32-4417-9d72-7475bb96517e".guid();

var guidanceItemHtml = tmWebServices.GetGuidanceItemHtml(guidanceItemID);

return "{0}".format(guidanceItemHtml);


//using O2.SecurityInnovation.TeamMentor
//O2File:TM_WebServices.cs
//O2File:Test_TM_Config.cs
//O2Ref:System.Web.Services.dll

关键是添加

tmWebServices.CookieContainer = new System.Net.CookieContainer();

使得从服务器发送的cookie在进一步请求时重新发送。

在上面的示例中,如果在没有有效会话cookie值的情况下调用GetGuidanceItemHtml,您将收到安全性异常(服务器端存在CAS安全性要求)