使用ASP.NET网站中托管的WCF服务

时间:2013-08-05 18:08:34

标签: wcf

我获得了一个在ASP.NET网站中托管的WCF服务。该服务仅在有人登录该网站时可用.WCF服务使用webHttp绑定。现在我需要从其他M / c的控制台应用程序中使用服务。我有登录网站的身份验证凭据(用户名/密码)。无论如何,我可以使用凭据从控制台应用程序中使用服务吗?作为先决条件,我无法改变服务方面的任何内容。

1 个答案:

答案 0 :(得分:0)

这项技术对我有用,因为使用表单身份验证的页面背后的代码是调用我们的WCF服务来进行实际的登录处理,即我们已经制作了OperationContract

    string address = "http://localhost:4567";
    var serviceClient = new SomeService.MyServiceClient(
        "BasicHttpBinding_IMyService", address + "/myservice.svc");

    // Call the service login method, save off the response's cookie(s)
    string cookiesFromLogin = string.Empty;
    bool logonSucceeded = false;
    using (new OperationContextScope(serviceClient.InnerChannel))
    {
        logonSucceeded = serviceClient.DoTheLogin("userName", "userPass");

        var httpResponse = (HttpResponseMessageProperty)
            OperationContext.Current.IncomingMessageProperties[
                HttpResponseMessageProperty.Name];
        cookiesFromLogin = httpResponse.Headers["Set-Cookie"];
    }

    // Then later when you need to make other service calls, insert the cookie(s)
    // into the request headers
    using (new OperationContextScope(serviceClient.InnerChannel))
    {
        var httpRequest = new HttpRequestMessageProperty();
        httpRequest.Headers["Cookie"] = cookiesFromLogin;
        OperationContext.Current.OutgoingMessageProperties[
            HttpRequestMessageProperty.Name] = httpRequest;

        var someResults = serviceClient.CallSomeMethod("param1");
    }