繁体   English   中英

使用C#从Windows应用程序调用Java Web服务时如何在请求中设置Cookie

[英]How do i set cookie in the request while invoking a java webservice from a windows application using c#

使用C#从Windows应用程序调用Java Web服务时,如何在请求中设置Cookie。 我想在调用Java Web服务时将JSESSIONID作为cookie在HttpHeader中传递。 我有JSESSIONID。 我想知道如何创建一个cookie并在请求中传递它。

有人可以建议我。 可行吗

如果使用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生成客户端,则可以在此处查看


更新:

实际上,无需强制转换为HttpWebRequest即可添加自定义标头:

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

该答案主要基于达林·迪米特洛夫(Darin Dimitrov)的答案-如果您觉得有用,请提高他的答案。

在我的情况下,Web服务希望将JSESSIONID值用作Cookie,而不是其他标头值。

我的WCF客户端也使用Visual Studio的“项目-设置服务参考”工具生成的代理代码,我相信这与使用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();
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM