如何使WCF服务与https一起使用?

时间:2014-11-05 15:46:48

标签: c# web-services wcf ssl https

我正在尝试在我的WCF服务中启用https。我已经将SSL证书添加到我的localhost中,并且当我在浏览器中使用https时,我能够查看WSDL。并且在Web.config中没有SSL配置的情况下,WCF服务可以正常使用http。但是一旦我将其更改为使用https,我就会收到以下错误。如果有人可以指出我对这个问题的解决方案,那将会有所帮助,因为没有太多关于此错误的参考。

at Microsoft.Http.HttpStageProcessingAsyncResult.Complete(HttpStage stage, Exception e)
at Microsoft.Http.HttpStageProcessingAsyncResult.NextRequest(HttpStageProcessingAsyncResult self)
at Microsoft.Http.HttpStageProcessingAsyncResult..ctor(HttpStageProcessingAsyncState state, AsyncCallback callback, Object user)
at Microsoft.Http.HttpClient.Send(HttpRequestMessage request)
at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri, RequestHeaders headers, HttpContent content)
at Microsoft.Http.HttpClient.Send(HttpMethod method, Uri uri)
at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, Uri uri)
at Microsoft.Http.HttpMethodExtensions.Method(HttpClient client, HttpMethod method, String uri)
at Microsoft.Http.HttpMethodExtensions.Get(HttpClient client, String uri)
at MobileScreening.Client.CommonTests.LoginPost(HttpClient client, String username, String password) in c:\TFS Projects\MobileScreening\MobileScreening.Client\CommonTests.cs:line 118

我向客户提供服务请求的客户端代码

static string LoginPost(HttpClient client, string username, string password)
    {
        string key = string.Empty;

        try
        {
            var user = new UserCredentials
            {
                Email = username,
                Password = password
            };

            Console.WriteLine("User Authentication:");

            HttpContent content = HttpContentExtensions.CreateJsonDataContract(user);

            using (HttpResponseMessage response = client.Post("AuthenticationService.svc/", content))
            {
                Console.WriteLine(response.Content.ReadAsString());
                Console.WriteLine(response.Headers.ToString());

                key = response.Headers["MobileScreening"] ?? string.Empty;
            }
        }
        catch (Exception ex)
        {
            var stack = ex.StackTrace;
            var innerException = ex.InnerException;
            var message = ex.Message;
        }

        return key;
    }

我与操作合同的界面

public interface IAuthenticationService
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    AuthenticationWrapper Authenticate(UserCredentials user);
}

我的用户身份验证服务:

public class AuthenticationService : IAuthenticationService
{
    public AuthenticationWrapper Authenticate(UserCredentials user)
    {
        string email = user.Email ?? string.Empty;
        string password = user.Password ?? string.Empty;

        var authentication = new Authentication();

        var authenticationWrapper = new AuthenticationWrapper();

        if (!authentication.AuthenticateUser(email, password))
        {
            const string description = "Authentication failed. Username and/or password is incorrect.";

            BLL.Authentication.ThrowAuthorisationFailed(description, email);

            WebOperationContext ctx = WebOperationContext.Current;
            ctx.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;

            authenticationWrapper.Code = (short)HttpStatusCode.Unauthorized;
            authenticationWrapper.Status = HttpStatusCode.Unauthorized.ToString();
            authenticationWrapper.Message = description;
            return authenticationWrapper;
        }
        else
        {
            const string description = "Authentication: Authenticate User";

            LogHandler.LogMessage(email, description, Common.Event.LoginSuccessful);

            string authorisationKey = authentication.CreateAuthorisationKey(email);

            WebOperationContext ctx = WebOperationContext.Current;
            ctx.OutgoingResponse.Headers.Add(Common.AuthorisationHeader, authorisationKey);
            ctx.OutgoingResponse.StatusCode = HttpStatusCode.OK;

            authenticationWrapper.Code = (short)HttpStatusCode.OK;
            authenticationWrapper.Status = HttpStatusCode.OK.ToString();
            authenticationWrapper.Message = description;
            return authenticationWrapper;
        }
    }
}

最后我的服务的web.config配置

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />
<services>
  <service name="MobileScreening.ServiceApp.AuthenticationService">
    <endpoint address="AuthenticationService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IAuthenticationService" />
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
  <service name="MobileScreening.ServiceApp.ProgrammeService">
    <endpoint address="ProgrammeService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IProgrammeService" />
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
  <service name="MobileScreening.ServiceApp.ActivityService">
    <endpoint address="ActivityService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IActivityService" />
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
  <service name="MobileScreening.ServiceApp.UserConfigurationService">
    <endpoint address="UserConfigurationService" binding="basicHttpBinding" bindingConfiguration="secureHttpBinding" contract="MobileScreening.ServiceApp.IUserConfigurationService" />
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding name="secureHttpBinding">
      <security mode="Transport">
        <transport clientCredentialType="Basic"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpsGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
</system.serviceModel>

1 个答案:

答案 0 :(得分:1)

使用您的计算机名称而不是本地主机创建新的自签名证书。配置您的解决方案以使用新证书,并确保它安装在受信任的根证书颁发机构下的客户端计算机中(在您的情况下,客户端也是服务器)。

此外,您还可以尝试创建指向计算机完全限定域名的证书。