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

标签 .net web-services soap cookiecontainer

我在 .NET 中将 cookie 设置为 Web 服务调用时遇到问题。在使用提供的 wsdl 的任何调用之前,我必须提供一个在登录到客户网站时获得的 cookie。我有一个方法来登录和检索 cookie,然后我将它传递给我的 makeSearch 方法(如下所示)。如您所见,我正在 cookieContainer 中为 wsdl 对象设置 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;
}

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

最佳答案

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

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 安全需求)

关于.net - 通过 .NET 中的 Web 服务调用发送 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8719426/

相关文章:

c# - 如何让 SourceAFIS 在 Ubuntu 上运行?

c# - c# .net Compact Framework 3.5 中最快的字典查找

web-services - 标准 Web 服务 v 安全 Web 服务

java - JPA 中检测到的对象图中的循环

ajax - 为什么使用 wsHttpBinding 时 InstanceContextMode.PerSession 的行为类似于 PerCall?

c# - 未处理的异常,MySql.Data.MySqlClient.MySqlException

.net - 如何正确地散列字符串

java - 在 Eclipse 动态 Web 项目中包含 HTML 文件

java - 从 SOAP 请求中删除可选标签时失败

java - 我需要在 java 中创建一个 Web 应用程序,它使用基于 SOAP 的 .Net Web 服务。为此,我将使用哪种工具和框架?