如何使用c#从Windows应用程序调用java webservice时在请求中设置cookie

时间:2009-09-22 12:30:36

标签: c# cookies

如何在使用c#从Windows应用程序调用java webservice时在请求中设置cookie。我想在调用java webservice时将JSESSIONID作为cookie传递给HttpHeader。我有JSESSIONID。我想知道如何创建一个cookie并在请求中传递它。

有人可以建议我吗?是否可行。

2 个答案:

答案 0 :(得分:4)

如果您使用WCF生成客户端代理(svcutil.exe),您可以在您的请求中添加自定义http标头,如下所示:

// MyServiceClient is the class generated by svcutil.exe which derives from
// System.ServiceModel.ClientBase<TServiceContract> and which allows you to
// call the web service methods
using (var client = new MyServiceClient())
using (var scope = new OperationContextScope(client.InnerChannel))
{
    var httpRequestProperty = new HttpRequestMessageProperty();
    // Set the header value
    httpRequestProperty.Headers.Add("JSESSIONID", "XXXXX");
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

    // Invoke the method
    client.SomeMethod();
}

如果您使用wsdl.exe生成客户端,可以查看here


更新:

实际上没有必要强制转换为HttpWebRequest来添加自定义标题:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    WebRequest request = base.GetWebRequest(uri);
    request.Headers.Add("JSESSIONID", "XXXXX");
    return request;
}

答案 1 :(得分:1)

这个答案很大程度上是基于达林迪米特罗夫的答案 - 如果你发现它有用,请提出他的答案。

在我的情况下,Web服务需要将JSESSIONID值作为cookie,而不是杂项标题值。

我的WCF客户端也在使用Visual Studio的Project-Set Service Reference工具生成的代理代码,我认为这与使用wsdl.exe程序相同。

  // Session ID received from web service as response to authentication login
  private string _sessionId;


     // This code needed to add the session ID to the HTTP header as a JSESSIONID cookie value
     using (MyServiceClient myServiceClient = new MyServiceClient())
     using (new OperationContextScope(myServiceClient.InnerChannel))
     {
        HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
        httpRequestProperty.Headers.Add("Cookie", "JSESSIONID=" + _sessionId);
        OperationContext.Current.OutgoingMessageProperties.Add(
                                          HttpRequestMessageProperty.Name, httpRequestProperty);

        myServiceClient.someMethod();
     }