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

4
我在使用.NET调用web服务时遇到了设置cookie的问题。在使用提供的wsdl调用之前,我必须提供一个cookie,该cookie是在登录客户网站时获得的。我有一个方法来登录并检索cookie,然后将其传递给我的makeSearch方法(如下所示)。正如您所看到的,我正在为wsdl对象中的cookieContainer设置cookie;但是,当我检查AdvancedSearch方法发出的请求时,在fiddler中注意到没有发送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;
}

有人能列出任何想法或解决方案吗?


看起来你没有正确设置cookie。cookie字符串值是cookie本身的内容还是仅仅是名称参数? - Alan
这是cookie字符串值的内容。传递到makeSearch()方法中的cookie字符串值是由另一个方法检索的。还有其他方法吗? - Javier Gonzalez
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 将会被重发,导致了上述情况。在上面的例子中,如果你在调用 GetGuidanceItemHtml 时没有有效的 Session cookie 值,你将会收到一个安全异常(因为服务器端有 CAS 安全要求)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接