4

我在将 cookie 设置为 .NET 中的 Web 服务调用时遇到问题。在使用所提供的 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;
}

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

4

1 回答 1

5

我刚刚遇到了同样的问题,这就是我解决它的方法

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 在进一步请求时重新发送。

在上面的示例中,如果您在没有有效 Session cookie 值的情况下调用 GetGuidanceItemHtml,您将得到一个安全异常(服务器端有 CAS 安全需求)

于 2012-01-17T14:23:24.640 回答