这是跨域ajax请求:
$.ajax({
type: "POST",
dataType: "jsonp",
contentType: "application/jsonp",
data: '{"UserName":"newuser","Password":"pwd"}',
crossDomain: true,
async: false,
url: "http://xxx.xx.xx.xx/MyService/SampleService.svc/GetData",
jsonpCallback: function (jsonData) {
console.log(jsonData);
alert('Hi');
},
complete: function (request, textStatus) {
alert(request.responseText);
alert(textStatus);
},
error: function (request, textStatus, errorThrown) {
alert(textStatus);
}
});
这是我的WCF REST服务的方法:
namespace SampleServiceRestAPI
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class SampleService : ISampleService
{
...
public string GetData(UserData userData)
{
string response = "Hi_" + userData.UserName;
return response;
}
...
}
接口:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetData")]
[OperationContract]
string GetData(UserData userData);
Datacontract:
[DataContract]
public class UserData
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password { get; set; }
}
web.config
的部分:
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.serviceModel>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
</standardEndpoints>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" >
<serviceActivations>
<add factory="System.ServiceModel.Activation.ServiceHostFactory" relativeAddress="SampleService.svc" service="SampleServiceRestAPI.SampleService"/>
</serviceActivations>
</serviceHostingEnvironment>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="SampleServiceRestAPI.SampleService">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
bindingConfiguration="webWinBinding" contract="SampleServiceRestAPI.ISampleService" />
</service>
<!--<service behaviorConfiguration="metadataBehavior" name="MyService">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>-->
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webWinBinding" maxBufferSize="2147483647" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647">
<readerQuotas maxArrayLength="100000" maxStringContentLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
<!--<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
<protocols>
<add name="HttpPost"/>
<add name="HttpPostLocalhost"/>
</protocols>
</webServices>
</scripting>
</system.web.extensions>-->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
<appSettings>
<add key="ErrorCodeFile" value="~/App_Data/ErrorCode.txt"/>
</appSettings>
我在Firebug中遇到的错误:
“NetworkError:500内部服务器错误 - http://173.161.176.229/MyService/SampleService.svc/GetData?callback=undefined& {%22UserName%22:%22newuser%22,%22Password%22:%22pwd%22}&amp; _ = 1369120080493”
答案 0 :(得分:0)
500错误表示服务器端有些错误。你应该检查那里出了什么问题。您可能需要查看WCF部分。也许这会有所帮助:http://msdn.microsoft.com/en-us/library/ms732023.aspx
答案 1 :(得分:0)
你不能通常(见后面)将HTTP POST发送到与原始域不同的域上的服务。这通常被称为Same origin policy概念,是浏览器安全限制
阻止访问不同网站上的大多数方法和属性
JSONP
可以插入一个<script>
标记,其中src
是JSONP请求的URL,这是一个HTTP GET请求。您看到的错误是因为浏览器正在尝试 GET 投放500 Internal Server Error
的资源,因为我认为该网址不支持GET
。
如果JavaScript和WCF服务位于同一个域中,则不需要使用JSONP,而应该能够进行常规$.ajax()
POST。
如果同一域上的JavaScript和WCF服务(不是)(允许跨域请求的一种方式)是在您的服务器上启用CORS 。另外,browser must also support it