【发布时间】:2014-05-01 17:27:54
【问题描述】:
我知道这看起来像是重复的问题。
在这里,我想使用 jquery ajax 调用我的 wcf 休息服务,并希望在休息服务中传递以 countryname 作为参数的国家对象。但是每当我使用 html 页面中的 jquery ajax 调用我的休息服务时。但它给了我错误405 method not allowed。我尝试了很多时间来解决它。但我能够解决这个错误。我正在尝试传递数据在 json 对象中。
Iservice.cs:
[OperationContract]
[WebInvoke(UriTemplate = "/AddCountry", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json)]
String AddCountry(tableCountry Country);
Service.cs
public string AddCountry(tableCountry Country)
{
//do Code.
}
Web.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" crossDomainScriptAccessEnabled="true">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webbehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="Service">
<endpoint address="rest" binding="webHttpBinding" contract="IService" bindingConfiguration="webHttpBinding" behaviorConfiguration="webbehaviour"/>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
Ajax 代码
$("document").ready(function(){
var country = {"CountryName":"Iran"};
$.ajax({
type: "POST",
url: "http://localhost:2293/ACFRestAjaxParsing/Service.svc/rest/AddCountry",
data: JSON.stringify({ Country: country }),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
我参考这个链接来解决这个错误Stackoverflow
如果有人知道我的这个错误,请帮助我。
提前致谢。
【问题讨论】:
-
与
jsonp你不应该使用type: "POST", -
当我只使用
json然后我得到这个错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. -
尝试另一种方式使用
jsonp和type:"get" -
但我想将数据发布到服务,那么我该如何使用获取服务。如果您有任何其他方式,请建议。我该如何使用。
-
什么是跨域请求。
标签: jquery asp.net ajax wcf rest