[英]How to post data to WCF Service using jquery Ajax?
我在使用JQUERY AJAX消费WCF服务时面临问题。 我知道这是跨域问题,已经阅读了很多关于它的解决方案。 但没有一个对我有用。 以下是所有相关代码。 有人可以帮帮我吗?
谢谢
[OperationContract]
[WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[return: MessageParameter(Name = "result")]
public ServiceSearchResponse GetSearchResults(ServiceSearchParams sParams)
{
/// search function
}
JQUERY:
$.ajax({
type: 'POST',
url: "http://myserviceurl.com/GetSearchResults",
data: p,
contentType: "application/json; charset=utf-8",
dataType: 'json',
crossDomain: true,
success: function (data) {
alert(data);
},
failure: function (response) {
alert('failed');
},
error: function (response) {
alert(JSON.stringify(response));
}
});
Webconfig:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultServiceBehavior">
<!--Added DefaultServiceBehavior referenced at service tag above-->
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="myserives.services.AppServicesAspNetAjaxBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="mypackage.services.MyServices">
<endpoint address="" behaviorConfiguration="myserives.services.AppServicesAspNetAjaxBehavior" binding="webHttpBinding"
bindingConfiguration="LargeSizeMessages" contract="myContractName" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="LargeSizeMessages" maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" crossDomainScriptAccessEnabled="true">
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
这是它的样子: http : //screencast.com/t/b7tsqld6
请参阅错误: http : //screencast.com/t/pWQNAlmMYS3
后期数据中没有任何内容。 虽然我发布数据。
---更新
看我的Global.asax ..我在这里做错了什么:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
EnableCrossDmainAjaxCall();
}
private void EnableCrossDmainAjaxCall()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
"*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials",
"true");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"1728000");
HttpContext.Current.Response.End();
}
}
这是一段工作代码。
接口
[ServiceContract]
public interface IDataService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
List<RequestData> GetUser(RequestData data);
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "UsersList/{id}",RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedResponse)]
RequestData UsersList(string id);
}
类实现接口
public class DataService : IDataService
{
public List<RequestData> GetUser(RequestData data)
{
List<RequestData> list = new List<RequestData>();
if (data.Name.ToUpper() == "MAIRAJ")
{
list.Add(new RequestData
{
Name = "Mairaj",
Age = 25,
Address = "Test Address"
});
list.Add(new RequestData
{
Name = "Ahmad",
Age = 25,
Address = "Test Address"
});
}
return list;
}
public RequestData UsersList(string userId)
{
return new RequestData
{
Name = "Mairaj",
Age = 25,
Address = "Test Address"
};
}
}
自定义类
因为我将此类的对象作为参数传递给方法并返回此对象所以我正在使用此。 你可能不需要它。
[DataContract]
public class RequestData
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Address { get; set; }
}
Web.Config中
<configuration>
<configSections>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="WCFWebApp.DataService">
<endpoint address="" binding="webHttpBinding" contract="WCFWebApp.IDataService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
</configuration>
这就是你如何称呼它
var Data = {
Name: "Mairaj",
Age: 20,
Address: "Test Address"
//userId:1
};
$.ajax({
type: "POST",
url: "/DataService.svc/GetUser",
dataType: "JSON",
data: JSON.stringify(Data),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Data is " + data);
},
error: function () {
}
});
您需要在web.config中更改服务类的名称,并在jquery代码中更改您将调用它的URL。
我会尝试设置Access-Control-Allow-Credentials:true i web.config。 还可以尝试将Access-Control-Allow-Headers设置为与jquery ajax调用匹配的标头。 应该是“application / json”,但请与fiddler(或类似)确认。 最后尝试设置Access-Control-Request-Method:POST
我讨厌类似的问题,在尝试了不同的设置后,我在web.config中找到了一个实际工作的组合。 祝好运 :)
UPDATE
此外,我将确保access-control-allow-credentials与其他参数的形式相同。 即访问控制允许凭证。 我真的没有任何来源,但以防万一:)
我会尝试不使用localhost。 使用正确的主机名在不同的服务器上设置测试环境。至少Chrome在localhost上处理cors时遇到问题。
根据http://www.html5rocks.com/en/tutorials/cors/ ,请求的Content-type应该是以下之一:
更新2
您可以尝试更多的事情:添加:
$.support.cors = true;
之前
$.ajax({ ...
我认为问题可以通过不正确的内容类型来解决。 当我对Sharepoint 2013服务器进行CORS设置时,我添加了这个并且一切正常:
headers: {
"accept": "application/json;odata=verbose;charset=utf-8",
"content-type":"application/json;odata=verbose;charset=utf-8"
},
该内容类型可能与您无关,但我可能很重要的是指定类似内容。
您需要在Access-Control-Allow-Origin
添加请求的域而不是*
, *
可能不适用于所有浏览器,因为它存在安全问题 - 即OPTIONS
请求中只允许请求的域,而不是*应该在选项中响应响应标题。 要解决此问题,您需要将该代码更改为以下内容。
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
用请求的域名替换http://localhost
,以编程方式执行此操作,您可以使用它 - HttpContext.Current.Request.Headers["Origin"].ToString()
。
我已经在我的博客中更详细地解释了这一点 - Blog , CodeProject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.