如何使WCF服务使用https

本文关键字:https 服务 何使 WCF | 更新日期: 2023-09-27 18:29:11

我正在尝试在WCF服务中启用https。我已经将SSL证书添加到了本地主机,当我在浏览器中使用https时,我可以查看WSDL。WCF服务在web.config中没有SSL配置的情况下可以很好地使用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>

如何使WCF服务使用https

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

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