[英]Can not call to Wcf Service from JavaScript
我有一個WCF
服務,我通過使用Jquery
調用通過JS
使用它。
代碼如下:
IService1.cs:
[ServiceContract]
public interface IService1
{
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
User GetUser(string userName, string password);
}
Service1.cs:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public User GetUser(string userName, string password)
{
//DO SOMETHING
}
}
由IIS完成的托管:
<%@ ServiceHost Language="C#" Debug="true" Service="MyProjectName.Service1" CodeBehind="Service1.svc.cs" %>
Web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation debug="true"/>
<identity impersonate="false" />
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="MyProjectName.Service1"
behaviorConfiguration="ServiceBehavior">
<endpoint address=""
behaviorConfiguration="EndpBehavior"
binding="webHttpBinding"
contract="MyProjectName.IService1" />
</service>
</services>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
在我的Java腳本頁面中,我這樣調用GetUser
函數:
function CallService() {
jQuery.ajaxSetup({
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internal Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
var request = { userName: "aaa", password: "123" };
var jsondata = JSON.stringify(request);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:xxxx/Service1.svc/GetUser", // Location of the service
data: jsondata, //Data sent to server
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
crossDomain: true, //True or False
success: function (result) {
alert('success');
}
});
}
盡管可以在瀏覽器中啟動該服務,但仍會收到錯誤消息:
您離線! 請檢查您的網絡。
我找不到任何可以幫助我解決問題的方法,有人有想法嗎?
我認為您的問題是您的WS不允許跨域訪問。
您可以嘗試將下一個代碼添加到Web.config中 :
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
<!-- Rest of your code -->
</configuration>
不知道您是否嘗試過,但使用jsonp進行跨站點腳本編寫。
這是我在網上找到的示例。 XSS-WCF-From-JQuery
使用JSONP是一種解決由相同來源策略施加的限制的技術。 JSONP有其優點和缺點。 花一些時間研究其他方法,這些方法可能會更好地滿足您的項目需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.