从Jquery ajax访问传输层安全的Windows通信服务

时间:2015-08-10 12:05:13

标签: jquery asp.net ajax wcf ssl

我正在尝试使用来自ajax的asp.net网站的自签名证书来访问传输层安全的wcf服务。我已经在控制台应用程序中使用https协议测试了该服务,它运行正常。它返回值没有任何错误。当我尝试从jquery ajax访问相同的服务,发生错误表明服务器响应状态为405(方法不允许)。我不知道为什么和我读过很多博客但是无法解决问题。

以下是我的WCF服务代码以及配置文件:

WCF服务代码:

接口代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

    namespace EmployeeService
    {
        [ServiceContract(Namespace = "")]    
        public interface IEmployeeService
        {

            [OperationContract]
            string ShowName(string name);
        }
    }

课程代码:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using EmployeeLibrary;

namespace EmployeeService
{
   [System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
    public class EmployeeService : IEmployeeService
    {
       public string ShowName(string name)
       {
           EmployeeController controller = new EmployeeController();
           return controller.ShowName(name);
       }
    }
}

WCF Web.config文件:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="EmployeeService.EmployeeService" behaviorConfiguration="SecureEmployeeServiceBehaviour">
        <endpoint address="" behaviorConfiguration="EmployeeService.Service2AspNetAjaxBehavior"
          binding="webHttpBinding" contract="EmployeeService.IEmployeeService" bindingConfiguration="SecureEmployeeServiceBinding">
          <!--<identity>
            <certificate encodedValue=""/>
          </identity>-->
        </endpoint>
        <endpoint address="wh"
          binding="wsHttpBinding" contract="EmployeeService.IEmployeeService" bindingConfiguration="wssecureHttpsBinding" />
        <!--<host>
          <baseAddresses>
            <add baseAddress="https://secureservicewcfserver.com/EmployeeService.svc/"/>
          </baseAddresses>
        </host>-->
      </service>      
    </services>    
    <bindings>
      <webHttpBinding>
        <binding name="SecureEmployeeServiceBinding" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00" allowCookies="true">
          <security mode="Transport">
            <transport clientCredentialType="Certificate" proxyCredentialType="Windows">
              <!--<extendedProtectionPolicy policyEnforcement="Always"></extendedProtectionPolicy>-->
            </transport>
          </security>
        </binding>
      </webHttpBinding>
      <wsHttpBinding>
        <binding name="wssecureHttpsBinding" allowCookies="true" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00">
          <security mode="Transport">
            <transport clientCredentialType="Certificate" proxyCredentialType="Windows" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="SecureEmployeeServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceCredentials>
            <serviceCertificate findValue="secureservicewcfserver.com" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
            <clientCertificate>
              <authentication certificateValidationMode="PeerOrChainTrust" trustedStoreLocation="LocalMachine" revocationMode="Online" mapClientCertificateToWindowsAccount="false"/>
            </clientCertificate>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>      
      <endpointBehaviors>
        <behavior name="EmployeeService.Service2AspNetAjaxBehavior">
          <webHttp defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
          <enableWebScript />
        </behavior>
      </endpointBehaviors>      
    </behaviors>
    <protocolMapping>
      <add binding="wsHttpBinding" scheme="https" />
      <add binding="webHttpBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />
      </webScriptEndpoint>
    </standardEndpoints>
  </system.serviceModel>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

使用上面的配置和代码,当我尝试从控制台应用程序访问服务时,它工作正常并返回结果。

以下是配置文件的控制台应用程序代码:

控制台代码:

using System;
using System.Collections.Generic;

namespace SecuredWCFServiceConsoleConsumerApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeServices.EmployeeServiceClient client = new EmployeeServices.EmployeeServiceClient("WSHttpBinding_IEmployeeService");
            string myName = client.ShowName("Shrawan");
            Console.WriteLine(myName);
            Console.ReadLine();
        }
    }
}

App.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>

        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IEmployeeService" openTimeout="00:03:00" closeTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00">
                    <security mode="Transport">
                        <transport clientCredentialType="Certificate" proxyCredentialType="Windows" />
                    </security>
                </binding>
            </wsHttpBinding>

          <webHttpBinding>
            <binding name="webHttpBindingSecure" openTimeout="00:03:00" closeTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00">
              <security mode="Transport">
                <transport clientCredentialType="Certificate" proxyCredentialType="Windows" />
              </security>
            </binding>
          </webHttpBinding>
        </bindings>
        <client>
          <endpoint address="https://secureservicewcfserver.com/EmployeeService.svc/wh"
              binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IEmployeeService"
              contract="EmployeeServices.IEmployeeService" name="WSHttpBinding_IEmployeeService" behaviorConfiguration="clientSideSecureWCF">
            <identity>
              <dns value="secureservicewcfserver.com"/>
            </identity>
          </endpoint>
          <endpoint address="https://secureservicewcfserver.com/EmployeeService.svc/wh"
              binding="webHttpBinding" bindingConfiguration="webHttpBindingSecure"
              contract="EmployeeServices.IEmployeeService" name="webHttpBindingSecure_Service" behaviorConfiguration="clientSideSecureWCF">
            <identity>
              <dns value="secureservicewcfserver.com"/>
            </identity>
          </endpoint>
        </client>
      <behaviors>
        <endpointBehaviors>
          <behavior name="clientSideSecureWCF">
            <clientCredentials>
              <clientCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="SecuredWCFServiceClient"/>
              <serviceCertificate>
                <authentication certificateValidationMode="PeerOrChainTrust" trustedStoreLocation="LocalMachine" />
              </serviceCertificate>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
    </system.serviceModel>
</configuration>

现在,当我尝试使用jquery ajax从asp.net Web应用程序访问相同的服务时,发生错误,表明服务器响应状态为405(方法不允许)。

以下是我的配置文件的Web应用程序代码:

网络代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="SecureWCFServiceWebClient.Home" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #lblServiceOutput {
            font-size: 20px;
            color: chocolate;
        }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            debugger
            $.ajax({
                type: 'GET', //GET or POST or PUT or DELETE verb
                url: 'https://secureservicewcfserver.com/EmployeeService.svc/ShowName', // Location of the service
                data: JSON.stringify({ name: "Shrawan Lakhe" }), //Data sent to server
                contentType: 'application/jsonp; charset=utf-8', // content type sent to server
                dataType: 'jsonp', //Expected data format from server
                processdata: true, //True or False
                success: function (data) {//On Successfull service call
                    debugger
                    var name = data;
                    $('#lblServiceOutput').text(name);
                },
                error: function (msg) {
                    debugger// When Service call fails
                    alert(msg);
                }
            });
        });
    </script>
</head>
<body>
    <div class="divServiceResult">
        This is the test application for WCF Secure Application.
        <label id="lblServiceOutput"></label>
    </div>
</body>
</html>

Web.config代码

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IEmployeeService" openTimeout="00:03:00" closeTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00">
          <security mode="Transport">
            <transport clientCredentialType="Certificate" proxyCredentialType="Windows" />
          </security>
        </binding>
      </wsHttpBinding>
      <webHttpBinding>
        <binding name="webHttpBindingSecure" openTimeout="00:03:00" closeTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00">
          <security mode="Transport">
            <transport clientCredentialType="Certificate" proxyCredentialType="Windows" />
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://secureservicewcfserver.com/EmployeeService.svc/wh"
          binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IEmployeeService"
          contract="EmployeeServices.IEmployeeService" name="WSHttpBinding_IEmployeeService" behaviorConfiguration="clientSideSecureWCF">
        <identity>
          <dns value="secureservicewcfserver.com"/>
        </identity>
      </endpoint>
      <endpoint address="https://secureservicewcfserver.com/EmployeeService.svc/wh"
          binding="webHttpBinding" bindingConfiguration="webHttpBindingSecure"
          contract="EmployeeServices.IEmployeeService" name="webHttpBindingSecure_Service" behaviorConfiguration="clientSideSecureWCF">
        <identity>
          <dns value="secureservicewcfserver.com"/>
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="clientSideSecureWCF">
          <clientCredentials>
            <clientCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="SecuredWCFServiceClient"/>
            <serviceCertificate>
              <authentication certificateValidationMode="PeerOrChainTrust" trustedStoreLocation="LocalMachine" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

有关此问题的解决方案的任何帮助将非常感谢。我需要使用安全套接字层托管wcf服务和Web应用程序,如果是,我该怎么做?的由于

0 个答案:

没有答案