[英]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.