2

我有 .NET Framework 4 的 WCF REST 服务目标。我正在使用WebScriptEndPoint的标准端点并使用基本授权

当我使用 Jquery 使用此服务时,当我在同一个服务应用程序中拥有页面时,它工作正常,即http://localhost. 但是,如果我使用不同的 Web 应用程序使用此服务,即http://localhost:20984它无法正常工作。Fiddler 在我尝试时显示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

当我使用 Web 应用程序页面发送时,请参阅缺少授权标头。

看起来这是跨域问题。我确实启用了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>
4

1 回答 1

0

If you want to access the endpoint via jQuery, you should use the <webHttpEndpoint> standard endpoint, not the <webScriptEndpoint>. webScriptEndpoints should be used for clients which use the ASP.NET AJAX framework only.

于 2012-05-17T20:38:52.623 回答