【问题标题】:Consuming REST Service with WCF - Basic Authentication使用 WCF 使用 REST 服务 - 基本身份验证
【发布时间】:2012-10-29 11:19:11
【问题描述】:

我正在尝试使用带有基本身份验证的 REST 服务,但遇到了一个奇怪的问题。发出的第一个请求不包括指定的基本身份验证凭据。这发生在每个第一个请求中。每次应用程序启动时都会发生这种情况。后续请求不会发生这种情况。我正在使用ClientBase<T> 类来调用API,它看起来像这样:

public class MyApi : ClientBase<IMyApi>
{
    protected override IMyApi CreateChannel()
    {
        //Remove all client credentials. 
        ChannelFactory.Endpoint.Behaviors.RemoveAll<ClientCredentials>();

        //Create new client credentials and add to the endpoint behaviours.
        ClientCredentials clientCredentials = new ClientCredentials();
        clientCredentials.UserName.UserName = Username;
        clientCredentials.UserName.Password = Password;
        ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);

        return base.CreateChannel();
    }

    public MyApi() : base (DefaultEndpointName)
    {}
}

我的绑定设置如下:

  <customBinding>        
    <binding name="myApiBinding">
      <webMessageEncoding webContentTypeMapperType="ContentTypeMapper,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <httpTransport manualAddressing="true" maxReceivedMessageSize="6553600" authenticationScheme="Basic" realm="myRealm" />
    </binding>
  </customBinding>

我尝试将项目升级到 .Net 4,在初始化 API 后添加客户端凭据,但似乎没有一个具有预期的效果。

有没有办法为每个请求添加凭据?

【问题讨论】:

    标签: .net wcf c#-3.0


    【解决方案1】:

    this question

    第一个答案解释了原因...(服务器应该使用身份验证挑战响应第一个请求)

    第二个答案解释了如何解决...(通过操作请求 http 标头来手动插入基本身份验证凭据)

    【讨论】:

    • 看看答案,它似乎很冗长,因为它必须添加到 API 中的每个方法中?看起来OperationContextScope 是罪魁祸首。有没有办法将它添加到 CreateChannel 方法或构造函数中?我试过了,但看到了一些非常奇怪的结果。
    • 您也许可以在调用 base.CreateChannel() 之后在 CreateChannel() 方法中创建 OperationContextScope。只需记住覆盖 Dispose() 并释放您的 OperationContextScope。
    • 我尝试过,但无济于事。卡西尼号甚至一度坠毁。似乎唯一的方法是创建一个使用和处理 OperationContextScope 的通用方法,添加所需的标头并通过 Func 或类似的东西调用您所需的方法。
    猜你喜欢
    • 2011-01-13
    • 2013-12-19
    • 2011-09-24
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    相关资源
    最近更新 更多