使用Jquery的WCF4 REST跨域问题

时间:2012-05-17 15:52:37

标签: wcf wcf-client

我有针对.NET Framework 4的WCF REST服务目标。我使用 WebScriptEndPoint 的标准端点并使用基本身份验证

当我使用Jquery使用此服务时,当我在同一服务应用程序中使用该页面时,它正常工作,即http://localhost。但是,如果我使用不同的Web应用程序(即http://localhost:20984)使用此服务,则它无效。 当我尝试http://localhost/WebHttpBindTest/JSONAPIDemo.aspx

时,小提琴手会显示出来
GET http://localhost/WebHttpBindTest/Service.svc/GetData?value=some&callback=jsonp1337264181292&_=1337264186941 HTTP/1.1
Accept: text/javascript, application/javascript, */*
Accept-Language: en-us
Referer: http://localhost/WebHttpBindTest/JSONAPIDemo.aspx
Authorization: Basic Y2RtdXNlcjpjZG1wYXNzd29yZA==
x-requested-with: XMLHttpRequest
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)
Host: localhost
Connection: Keep-Alive
Cookie: __utma=37822774.11348549.1335971819.1337185885.1337195810.36; __utmz=37822774.1335971819.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

但是当我尝试使用网络应用时

GET http://localhost/WebHttpBindTest/Service.svc/GetData?value=fdsafa&callback=jsonp1337264499382&_=1337264533468 HTTP/1.1
Accept: application/javascript, */*;q=0.8
Referer: http://localhost:20984/WebSite1/Demo.htm
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Accept-Encoding: gzip, deflate
Host: localhost
Connection: Keep-Alive

使用网络应用页面发送时,请参阅授权标题。

看起来这是跨域问题。我确实启用了crossdomainscriptAccess,即

这是服务合同:

[ServiceContract]
public interface IService
{
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string GetData(string value);

}

的web.config

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service name="Service" behaviorConfiguration="auth">
        <endpoint address="" kind="webScriptEndpoint" contract="IService" />
      </service>
    </services>
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="true">
        </standardEndpoint>
      </webScriptEndpoint>
    </standardEndpoints>
    <behaviors>
      <serviceBehaviors>
        <behavior name="auth">
          <serviceAuthorization serviceAuthorizationManagerType="BasicAuth.BasicAuthorization, BasicAuth" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

JQuery表单:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Base64.js" type="text/javascript"></script>
    <script src="jquery.min.js" type="text/javascript" language="javascript"></script>
    <script type="text/javascript">
        var Type;
        var Url;
        var Data;
        var ContentType;
        var DataType;
        var ProcessData;
        function CallService(successfn,auth) {
            var addHeaders = function (xhr) {
                xhr.setRequestHeader("Authorization", auth);
            };

            $.ajax({
                type: Type, //GET or POST or PUT or DELETE verb
                url: Url, // Location of the service
                data: Data, //Data sent to server
                contentType: ContentType, // content type sent to server
                dataType: DataType, //Expected data format from server
                processdata: ProcessData, //True or False
                beforeSend: addHeaders,
                success: function (msg) {//On Successfull service call
                    successfn(msg);
                },
                error: ServiceFailed// When Service call fails
            });
        }
        function make_base_auth(user, pass) {
            var tok = user + ':' + pass;
            var hash = Base64.encode(tok);
            return "Basic " + hash;
        }
        function getUrl() {
            var auth = make_base_auth('user', 'password');
            Type = "GET";
            Url = "http://localhost/WebHttpBindTest/Service.svc/GetData?value=" + $('#txtCode').val();
            ContentType = "text/json; charset=utf-8";
            DataType = "jsonp";
            ProcessData = true;

            CallService(ServiceSucceeded,auth);
        }


        function ServiceSucceeded(result) {
            var resultObject = null;

            if (DataType == "jsonp") {
                if (Url.indexOf(".asmx/") > 0) {
                    resultObject = result.d; 
                }
                else {
                    $("#div1").html("Result:" + result);
                }
            }
        }
        function ServiceFailed(result) {
            alert('Service call failed: ' + result.status + '' + result.statusText);
            Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
        }
    </script>
</head>
<body>
    <div id="container">

        <h1>JSON API Demo</h1>

        <div>
            <p>Type Something: <input type="text" id="txtCode" />
            <button type="submit"value="submit" id="btnGetUrl" onclick="getUrl()">Get</button>
        </div>
        <br /><br />
        <center><div id="div1" style="font-size:larger"></div>  </center>
</div>  
</body>
</html>

1 个答案:

答案 0 :(得分:0)

如果要通过jQuery访问端点,则应使用<webHttpEndpoint>标准端点,而不是<webScriptEndpoint>webScriptEndpoint应该仅用于使用ASP.NET AJAX框架的客户端。