【问题标题】:Consuming a WCF Service Hosted in ASP.NET Website使用托管在 ASP.NET 网站中的 WCF 服务
【发布时间】:2013-08-07 09:21:25
【问题描述】:

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

【问题讨论】:

  • 您的 WCF 服务实现的任何部分是否使用 System.Web.HttpContext(传统 Web 会话)?您是否使用 ASP.NET 表单身份验证?如果是这样,那么控制台应用程序将需要模仿 Web 浏览器并在所有 WCF 请求上反射回 cookie。如果是这种情况,我可以提供一些代码来说明。症状将是,控制台将使用良好的身份验证成功登录,但在其他 WCF 请求上将失败,因为服务器端正在获取 null HttpContext
  • 嗨,你是对的。该网站正在使用表单身份验证。就我而言,我无法使用凭据调用该服务。我的理解是,由于网站使用表单身份验证,除了凭据之外,我们还需要 Cookie 信息。但是,我不知道如何获取网站使用的 Cookie 信息。请提供一些您所说的代码。

标签: wcf


【解决方案1】:

这种技术对我有用,因为页面中使用表单身份验证的代码正在调用我们的 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");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多